3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Parser Parser
29 * PHP Parser - Processes wiki markup (which uses a more user-friendly
30 * syntax, such as "[[link]]" for making links), and provides a one-way
31 * transformation of that wiki markup it into (X)HTML output / markup
32 * (which in turn the browser understands, and can display).
34 * There are seven main entry points into the Parser class:
37 * produces HTML output
38 * - Parser::preSaveTransform().
39 * produces altered wiki markup.
40 * - Parser::preprocess()
41 * removes HTML comments and expands templates
42 * - Parser::cleanSig() and Parser::cleanSigInSig()
43 * Cleans a signature before saving it to preferences
44 * - Parser::getSection()
45 * Return the content of a section from an article for section editing
46 * - Parser::replaceSection()
47 * Replaces a section by number inside an article
48 * - Parser::getPreloadText()
49 * Removes <noinclude> sections, and <includeonly> tags.
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
57 * $wgNamespacesWithSubpages
59 * @par Settings only within ParserOptions:
60 * $wgAllowExternalImages
61 * $wgAllowSpecialInclusion
69 * Update this version number when the ParserOutput format
70 * changes in an incompatible way, so the parser cache
71 * can automatically discard old data.
73 const VERSION
= '1.6.4';
76 * Update this version number when the output of serialiseHalfParsedText()
77 * changes in an incompatible way
79 const HALF_PARSED_VERSION
= 2;
81 # Flags for Parser::setFunctionHook
82 # Also available as global constants from Defines.php
83 const SFH_NO_HASH
= 1;
84 const SFH_OBJECT_ARGS
= 2;
86 # Constants needed for external link processing
87 # Everything except bracket, space, or control characters
88 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
89 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
90 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
91 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
92 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
94 # State constants for the definition list colon extraction
95 const COLON_STATE_TEXT
= 0;
96 const COLON_STATE_TAG
= 1;
97 const COLON_STATE_TAGSTART
= 2;
98 const COLON_STATE_CLOSETAG
= 3;
99 const COLON_STATE_TAGSLASH
= 4;
100 const COLON_STATE_COMMENT
= 5;
101 const COLON_STATE_COMMENTDASH
= 6;
102 const COLON_STATE_COMMENTDASHDASH
= 7;
104 # Flags for preprocessToDom
105 const PTD_FOR_INCLUSION
= 1;
107 # Allowed values for $this->mOutputType
108 # Parameter to startExternalParse().
109 const OT_HTML
= 1; # like parse()
110 const OT_WIKI
= 2; # like preSaveTransform()
111 const OT_PREPROCESS
= 3; # like preprocess()
113 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
115 # Marker Suffix needs to be accessible staticly.
116 const MARKER_SUFFIX
= "-QINU\x7f";
119 var $mTagHooks = array();
120 var $mTransparentTagHooks = array();
121 var $mFunctionHooks = array();
122 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
123 var $mFunctionTagHooks = array();
124 var $mStripList = array();
125 var $mDefaultStripList = array();
126 var $mVarCache = array();
127 var $mImageParams = array();
128 var $mImageParamsMagicArray = array();
129 var $mMarkerIndex = 0;
130 var $mFirstCall = true;
132 # Initialised by initialiseVariables()
135 * @var MagicWordArray
140 * @var MagicWordArray
143 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
145 # Cleared with clearState():
150 var $mAutonumber, $mDTopen;
157 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
159 * @var LinkHolderArray
164 var $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
166 var $mTplExpandCache; # empty-frame expansion cache
167 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
168 var $mExpensiveFunctionCount; # number of expensive parser function calls
169 var $mShowToc, $mForceTocPosition;
174 var $mUser; # User object; only used when doing pre-save transform
177 # These are variables reset at least once per parse regardless of $clearState
187 var $mTitle; # Title context, used for self-link rendering and similar things
188 var $mOutputType; # Output type, one of the OT_xxx constants
189 var $ot; # Shortcut alias, see setOutputType()
190 var $mRevisionObject; # The revision object of the specified revision ID
191 var $mRevisionId; # ID to display in {{REVISIONID}} tags
192 var $mRevisionTimestamp; # The timestamp of the specified revision ID
193 var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
194 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
195 var $mInputSize = false; # For {{PAGESIZE}} on current page.
203 * @var Array with the language name of each language link (i.e. the
204 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
205 * duplicate language links to the ParserOutput.
207 var $mLangLinkLanguages;
214 public function __construct( $conf = array() ) {
215 $this->mConf
= $conf;
216 $this->mUrlProtocols
= wfUrlProtocols();
217 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
218 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
219 if ( isset( $conf['preprocessorClass'] ) ) {
220 $this->mPreprocessorClass
= $conf['preprocessorClass'];
221 } elseif ( defined( 'HPHP_VERSION' ) ) {
222 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
223 $this->mPreprocessorClass
= 'Preprocessor_Hash';
224 } elseif ( extension_loaded( 'domxml' ) ) {
225 # PECL extension that conflicts with the core DOM extension (bug 13770)
226 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
227 $this->mPreprocessorClass
= 'Preprocessor_Hash';
228 } elseif ( extension_loaded( 'dom' ) ) {
229 $this->mPreprocessorClass
= 'Preprocessor_DOM';
231 $this->mPreprocessorClass
= 'Preprocessor_Hash';
233 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
237 * Reduce memory usage to reduce the impact of circular references
239 function __destruct() {
240 if ( isset( $this->mLinkHolders
) ) {
241 unset( $this->mLinkHolders
);
243 foreach ( $this as $name => $value ) {
244 unset( $this->$name );
249 * Allow extensions to clean up when the parser is cloned
252 wfRunHooks( 'ParserCloned', array( $this ) );
256 * Do various kinds of initialisation on the first call of the parser
258 function firstCallInit() {
259 if ( !$this->mFirstCall
) {
262 $this->mFirstCall
= false;
264 wfProfileIn( __METHOD__
);
266 CoreParserFunctions
::register( $this );
267 CoreTagHooks
::register( $this );
268 $this->initialiseVariables();
270 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
271 wfProfileOut( __METHOD__
);
279 function clearState() {
280 wfProfileIn( __METHOD__
);
281 if ( $this->mFirstCall
) {
282 $this->firstCallInit();
284 $this->mOutput
= new ParserOutput
;
285 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
286 $this->mAutonumber
= 0;
287 $this->mLastSection
= '';
288 $this->mDTopen
= false;
289 $this->mIncludeCount
= array();
290 $this->mArgStack
= false;
291 $this->mInPre
= false;
292 $this->mLinkHolders
= new LinkHolderArray( $this );
294 $this->mRevisionObject
= $this->mRevisionTimestamp
=
295 $this->mRevisionId
= $this->mRevisionUser
= null;
296 $this->mVarCache
= array();
298 $this->mLangLinkLanguages
= array();
301 * Prefix for temporary replacement strings for the multipass parser.
302 * \x07 should never appear in input as it's disallowed in XML.
303 * Using it at the front also gives us a little extra robustness
304 * since it shouldn't match when butted up against identifier-like
307 * Must not consist of all title characters, or else it will change
308 * the behavior of <nowiki> in a link.
310 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
311 $this->mStripState
= new StripState( $this->mUniqPrefix
);
313 # Clear these on every parse, bug 4549
314 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
316 $this->mShowToc
= true;
317 $this->mForceTocPosition
= false;
318 $this->mIncludeSizes
= array(
322 $this->mPPNodeCount
= 0;
323 $this->mGeneratedPPNodeCount
= 0;
324 $this->mHighestExpansionDepth
= 0;
325 $this->mDefaultSort
= false;
326 $this->mHeadings
= array();
327 $this->mDoubleUnderscores
= array();
328 $this->mExpensiveFunctionCount
= 0;
331 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
332 $this->mPreprocessor
= null;
335 wfRunHooks( 'ParserClearState', array( &$this ) );
336 wfProfileOut( __METHOD__
);
340 * Convert wikitext to HTML
341 * Do not call this function recursively.
343 * @param string $text text we want to parse
344 * @param $title Title object
345 * @param $options ParserOptions
346 * @param $linestart boolean
347 * @param $clearState boolean
348 * @param int $revid number to pass in {{REVISIONID}}
349 * @return ParserOutput a ParserOutput
351 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
353 * First pass--just handle <nowiki> sections, pass the rest off
354 * to internalParse() which does all the real work.
357 global $wgUseTidy, $wgAlwaysUseTidy;
358 $fname = __METHOD__
. '-' . wfGetCaller();
359 wfProfileIn( __METHOD__
);
360 wfProfileIn( $fname );
362 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
364 $this->mInputSize
= strlen( $text );
365 if ( $this->mOptions
->getEnableLimitReport() ) {
366 $this->mOutput
->resetParseStartTime();
369 # Remove the strip marker tag prefix from the input, if present.
371 $text = str_replace( $this->mUniqPrefix
, '', $text );
374 $oldRevisionId = $this->mRevisionId
;
375 $oldRevisionObject = $this->mRevisionObject
;
376 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
377 $oldRevisionUser = $this->mRevisionUser
;
378 if ( $revid !== null ) {
379 $this->mRevisionId
= $revid;
380 $this->mRevisionObject
= null;
381 $this->mRevisionTimestamp
= null;
382 $this->mRevisionUser
= null;
385 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
387 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
388 $text = $this->internalParse( $text );
389 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
391 $text = $this->mStripState
->unstripGeneral( $text );
393 # Clean up special characters, only run once, next-to-last before doBlockLevels
395 # french spaces, last one Guillemet-left
396 # only if there is something before the space
397 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
398 # french spaces, Guillemet-right
399 '/(\\302\\253) /' => '\\1 ',
400 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
402 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
404 $text = $this->doBlockLevels( $text, $linestart );
406 $this->replaceLinkHolders( $text );
409 * The input doesn't get language converted if
411 * b) Content isn't converted
412 * c) It's a conversion table
413 * d) it is an interface message (which is in the user language)
415 if ( !( $options->getDisableContentConversion()
416 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) ) )
418 if ( !$this->mOptions
->getInterfaceMessage() ) {
419 # The position of the convert() call should not be changed. it
420 # assumes that the links are all replaced and the only thing left
421 # is the <nowiki> mark.
422 $text = $this->getConverterLanguage()->convert( $text );
427 * A converted title will be provided in the output object if title and
428 * content conversion are enabled, the article text does not contain
429 * a conversion-suppressing double-underscore tag, and no
430 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
431 * automatic link conversion.
433 if ( !( $options->getDisableTitleConversion()
434 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
435 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
436 ||
$this->mOutput
->getDisplayTitle() !== false ) )
438 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
439 if ( $convruletitle ) {
440 $this->mOutput
->setTitleText( $convruletitle );
442 $titleText = $this->getConverterLanguage()->convertTitle( $title );
443 $this->mOutput
->setTitleText( $titleText );
447 $text = $this->mStripState
->unstripNoWiki( $text );
449 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
451 $text = $this->replaceTransparentTags( $text );
452 $text = $this->mStripState
->unstripGeneral( $text );
454 $text = Sanitizer
::normalizeCharReferences( $text );
456 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
457 $text = MWTidy
::tidy( $text );
459 # attempt to sanitize at least some nesting problems
460 # (bug #2702 and quite a few others)
462 # ''Something [http://www.cool.com cool''] -->
463 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
464 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
465 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
466 # fix up an anchor inside another anchor, only
467 # at least for a single single nested link (bug 3695)
468 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
469 '\\1\\2</a>\\3</a>\\1\\4</a>',
470 # fix div inside inline elements- doBlockLevels won't wrap a line which
471 # contains a div, so fix it up here; replace
472 # div with escaped text
473 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
474 '\\1\\3<div\\5>\\6</div>\\8\\9',
475 # remove empty italic or bold tag pairs, some
476 # introduced by rules above
477 '/<([bi])><\/\\1>/' => '',
480 $text = preg_replace(
481 array_keys( $tidyregs ),
482 array_values( $tidyregs ),
486 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
487 $this->limitationWarn( 'expensive-parserfunction',
488 $this->mExpensiveFunctionCount
,
489 $this->mOptions
->getExpensiveParserFunctionLimit()
493 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
495 # Information on include size limits, for the benefit of users who try to skirt them
496 if ( $this->mOptions
->getEnableLimitReport() ) {
497 $max = $this->mOptions
->getMaxIncludeSize();
499 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
500 if ( $cpuTime !== null ) {
501 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
502 sprintf( "%.3f", $cpuTime )
506 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
507 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
508 sprintf( "%.3f", $wallTime )
511 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
512 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
514 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
515 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
517 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
518 array( $this->mIncludeSizes
['post-expand'], $max )
520 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
521 array( $this->mIncludeSizes
['arg'], $max )
523 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
524 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
526 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
527 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
529 wfRunHooks( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
531 $limitReport = "NewPP limit report\n";
532 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
533 if ( wfRunHooks( 'ParserLimitReportFormat',
534 array( $key, $value, &$limitReport, false, false )
536 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
537 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
538 ->inLanguage( 'en' )->useDatabase( false );
539 if ( !$valueMsg->exists() ) {
540 $valueMsg = new RawMessage( '$1' );
542 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
543 $valueMsg->params( $value );
544 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
548 // Since we're not really outputting HTML, decode the entities and
549 // then re-encode the things that need hiding inside HTML comments.
550 $limitReport = htmlspecialchars_decode( $limitReport );
551 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
553 // Sanitize for comment. Note '‐' in the replacement is U+2010,
554 // which looks much like the problematic '-'.
555 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
556 $text .= "\n<!-- \n$limitReport-->\n";
558 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
559 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
560 $this->mTitle
->getPrefixedDBkey() );
563 $this->mOutput
->setText( $text );
565 $this->mRevisionId
= $oldRevisionId;
566 $this->mRevisionObject
= $oldRevisionObject;
567 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
568 $this->mRevisionUser
= $oldRevisionUser;
569 $this->mInputSize
= false;
570 wfProfileOut( $fname );
571 wfProfileOut( __METHOD__
);
573 return $this->mOutput
;
577 * Recursive parser entry point that can be called from an extension tag
580 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
582 * @param string $text text extension wants to have parsed
583 * @param $frame PPFrame: The frame to use for expanding any template variables
587 function recursiveTagParse( $text, $frame = false ) {
588 wfProfileIn( __METHOD__
);
589 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
590 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
591 $text = $this->internalParse( $text, false, $frame );
592 wfProfileOut( __METHOD__
);
597 * Expand templates and variables in the text, producing valid, static wikitext.
598 * Also removes comments.
599 * @return mixed|string
601 function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null ) {
602 wfProfileIn( __METHOD__
);
603 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
604 if ( $revid !== null ) {
605 $this->mRevisionId
= $revid;
607 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
608 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
609 $text = $this->replaceVariables( $text );
610 $text = $this->mStripState
->unstripBoth( $text );
611 wfProfileOut( __METHOD__
);
616 * Recursive parser entry point that can be called from an extension tag
619 * @param string $text text to be expanded
620 * @param $frame PPFrame: The frame to use for expanding any template variables
624 public function recursivePreprocess( $text, $frame = false ) {
625 wfProfileIn( __METHOD__
);
626 $text = $this->replaceVariables( $text, $frame );
627 $text = $this->mStripState
->unstripBoth( $text );
628 wfProfileOut( __METHOD__
);
633 * Process the wikitext for the "?preload=" feature. (bug 5210)
635 * "<noinclude>", "<includeonly>" etc. are parsed as for template
636 * transclusion, comments, templates, arguments, tags hooks and parser
637 * functions are untouched.
639 * @param $text String
640 * @param $title Title
641 * @param $options ParserOptions
644 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
645 # Parser (re)initialisation
646 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
648 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
649 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
650 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
651 $text = $this->mStripState
->unstripBoth( $text );
656 * Get a random string
660 public static function getRandomString() {
661 return wfRandomString( 16 );
665 * Set the current user.
666 * Should only be used when doing pre-save transform.
668 * @param $user Mixed: User object or null (to reset)
670 function setUser( $user ) {
671 $this->mUser
= $user;
675 * Accessor for mUniqPrefix.
679 public function uniqPrefix() {
680 if ( !isset( $this->mUniqPrefix
) ) {
681 # @todo FIXME: This is probably *horribly wrong*
682 # LanguageConverter seems to want $wgParser's uniqPrefix, however
683 # if this is called for a parser cache hit, the parser may not
684 # have ever been initialized in the first place.
685 # Not really sure what the heck is supposed to be going on here.
687 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
689 return $this->mUniqPrefix
;
693 * Set the context title
697 function setTitle( $t ) {
698 if ( !$t ||
$t instanceof FakeTitle
) {
699 $t = Title
::newFromText( 'NO TITLE' );
702 if ( strval( $t->getFragment() ) !== '' ) {
703 # Strip the fragment to avoid various odd effects
704 $this->mTitle
= clone $t;
705 $this->mTitle
->setFragment( '' );
712 * Accessor for the Title object
714 * @return Title object
716 function getTitle() {
717 return $this->mTitle
;
721 * Accessor/mutator for the Title object
723 * @param $x Title object or null to just get the current one
724 * @return Title object
726 function Title( $x = null ) {
727 return wfSetVar( $this->mTitle
, $x );
731 * Set the output type
733 * @param $ot Integer: new value
735 function setOutputType( $ot ) {
736 $this->mOutputType
= $ot;
739 'html' => $ot == self
::OT_HTML
,
740 'wiki' => $ot == self
::OT_WIKI
,
741 'pre' => $ot == self
::OT_PREPROCESS
,
742 'plain' => $ot == self
::OT_PLAIN
,
747 * Accessor/mutator for the output type
749 * @param int|null $x New value or null to just get the current one
752 function OutputType( $x = null ) {
753 return wfSetVar( $this->mOutputType
, $x );
757 * Get the ParserOutput object
759 * @return ParserOutput object
761 function getOutput() {
762 return $this->mOutput
;
766 * Get the ParserOptions object
768 * @return ParserOptions object
770 function getOptions() {
771 return $this->mOptions
;
775 * Accessor/mutator for the ParserOptions object
777 * @param $x ParserOptions New value or null to just get the current one
778 * @return ParserOptions Current ParserOptions object
780 function Options( $x = null ) {
781 return wfSetVar( $this->mOptions
, $x );
787 function nextLinkID() {
788 return $this->mLinkID++
;
794 function setLinkID( $id ) {
795 $this->mLinkID
= $id;
799 * Get a language object for use in parser functions such as {{FORMATNUM:}}
802 function getFunctionLang() {
803 return $this->getTargetLanguage();
807 * Get the target language for the content being parsed. This is usually the
808 * language that the content is in.
812 * @throws MWException
813 * @return Language|null
815 public function getTargetLanguage() {
816 $target = $this->mOptions
->getTargetLanguage();
818 if ( $target !== null ) {
820 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
821 return $this->mOptions
->getUserLangObj();
822 } elseif ( is_null( $this->mTitle
) ) {
823 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
826 return $this->mTitle
->getPageLanguage();
830 * Get the language object for language conversion
832 function getConverterLanguage() {
833 return $this->getTargetLanguage();
837 * Get a User object either from $this->mUser, if set, or from the
838 * ParserOptions object otherwise
840 * @return User object
843 if ( !is_null( $this->mUser
) ) {
846 return $this->mOptions
->getUser();
850 * Get a preprocessor object
852 * @return Preprocessor instance
854 function getPreprocessor() {
855 if ( !isset( $this->mPreprocessor
) ) {
856 $class = $this->mPreprocessorClass
;
857 $this->mPreprocessor
= new $class( $this );
859 return $this->mPreprocessor
;
863 * Replaces all occurrences of HTML-style comments and the given tags
864 * in the text with a random marker and returns the next text. The output
865 * parameter $matches will be an associative array filled with data in
869 * 'UNIQ-xxxxx' => array(
872 * array( 'param' => 'x' ),
873 * '<element param="x">tag content</element>' ) )
876 * @param array $elements list of element names. Comments are always extracted.
877 * @param string $text Source text string.
878 * @param array $matches Out parameter, Array: extracted tags
879 * @param $uniq_prefix string
880 * @return String: stripped text
882 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
887 $taglist = implode( '|', $elements );
888 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
890 while ( $text != '' ) {
891 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
893 if ( count( $p ) < 5 ) {
896 if ( count( $p ) > 5 ) {
910 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
911 $stripped .= $marker;
913 if ( $close === '/>' ) {
914 # Empty element tag, <tag />
919 if ( $element === '!--' ) {
922 $end = "/(<\\/$element\\s*>)/i";
924 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
926 if ( count( $q ) < 3 ) {
927 # No end tag -- let it run out to the end of the text.
936 $matches[$marker] = array( $element,
938 Sanitizer
::decodeTagAttributes( $attributes ),
939 "<$element$attributes$close$content$tail" );
945 * Get a list of strippable XML-like elements
949 function getStripList() {
950 return $this->mStripList
;
954 * Add an item to the strip state
955 * Returns the unique tag which must be inserted into the stripped text
956 * The tag will be replaced with the original text in unstrip()
958 * @param $text string
962 function insertStripItem( $text ) {
963 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
964 $this->mMarkerIndex++
;
965 $this->mStripState
->addGeneral( $rnd, $text );
970 * parse the wiki syntax used to render tables
975 function doTableStuff( $text ) {
976 wfProfileIn( __METHOD__
);
978 $lines = StringUtils
::explode( "\n", $text );
980 $td_history = array(); # Is currently a td tag open?
981 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
982 $tr_history = array(); # Is currently a tr tag open?
983 $tr_attributes = array(); # history of tr attributes
984 $has_opened_tr = array(); # Did this table open a <tr> element?
985 $indent_level = 0; # indent level of the table
987 foreach ( $lines as $outLine ) {
988 $line = trim( $outLine );
990 if ( $line === '' ) { # empty line, go to next line
991 $out .= $outLine . "\n";
995 $first_character = $line[0];
998 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
999 # First check if we are starting a new table
1000 $indent_level = strlen( $matches[1] );
1002 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1003 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1005 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1006 array_push( $td_history, false );
1007 array_push( $last_tag_history, '' );
1008 array_push( $tr_history, false );
1009 array_push( $tr_attributes, '' );
1010 array_push( $has_opened_tr, false );
1011 } elseif ( count( $td_history ) == 0 ) {
1012 # Don't do any of the following
1013 $out .= $outLine . "\n";
1015 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1016 # We are ending a table
1017 $line = '</table>' . substr( $line, 2 );
1018 $last_tag = array_pop( $last_tag_history );
1020 if ( !array_pop( $has_opened_tr ) ) {
1021 $line = "<tr><td></td></tr>{$line}";
1024 if ( array_pop( $tr_history ) ) {
1025 $line = "</tr>{$line}";
1028 if ( array_pop( $td_history ) ) {
1029 $line = "</{$last_tag}>{$line}";
1031 array_pop( $tr_attributes );
1032 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1033 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1034 # Now we have a table row
1035 $line = preg_replace( '#^\|-+#', '', $line );
1037 # Whats after the tag is now only attributes
1038 $attributes = $this->mStripState
->unstripBoth( $line );
1039 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1040 array_pop( $tr_attributes );
1041 array_push( $tr_attributes, $attributes );
1044 $last_tag = array_pop( $last_tag_history );
1045 array_pop( $has_opened_tr );
1046 array_push( $has_opened_tr, true );
1048 if ( array_pop( $tr_history ) ) {
1052 if ( array_pop( $td_history ) ) {
1053 $line = "</{$last_tag}>{$line}";
1057 array_push( $tr_history, false );
1058 array_push( $td_history, false );
1059 array_push( $last_tag_history, '' );
1060 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line, 0, 2 ) === '|+' ) {
1061 # This might be cell elements, td, th or captions
1062 if ( substr( $line, 0, 2 ) === '|+' ) {
1063 $first_character = '+';
1064 $line = substr( $line, 1 );
1067 $line = substr( $line, 1 );
1069 if ( $first_character === '!' ) {
1070 $line = str_replace( '!!', '||', $line );
1073 # Split up multiple cells on the same line.
1074 # FIXME : This can result in improper nesting of tags processed
1075 # by earlier parser steps, but should avoid splitting up eg
1076 # attribute values containing literal "||".
1077 $cells = StringUtils
::explodeMarkup( '||', $line );
1081 # Loop through each table cell
1082 foreach ( $cells as $cell ) {
1084 if ( $first_character !== '+' ) {
1085 $tr_after = array_pop( $tr_attributes );
1086 if ( !array_pop( $tr_history ) ) {
1087 $previous = "<tr{$tr_after}>\n";
1089 array_push( $tr_history, true );
1090 array_push( $tr_attributes, '' );
1091 array_pop( $has_opened_tr );
1092 array_push( $has_opened_tr, true );
1095 $last_tag = array_pop( $last_tag_history );
1097 if ( array_pop( $td_history ) ) {
1098 $previous = "</{$last_tag}>\n{$previous}";
1101 if ( $first_character === '|' ) {
1103 } elseif ( $first_character === '!' ) {
1105 } elseif ( $first_character === '+' ) {
1106 $last_tag = 'caption';
1111 array_push( $last_tag_history, $last_tag );
1113 # A cell could contain both parameters and data
1114 $cell_data = explode( '|', $cell, 2 );
1116 # Bug 553: Note that a '|' inside an invalid link should not
1117 # be mistaken as delimiting cell parameters
1118 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1119 $cell = "{$previous}<{$last_tag}>{$cell}";
1120 } elseif ( count( $cell_data ) == 1 ) {
1121 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1123 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1124 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1125 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1129 array_push( $td_history, true );
1132 $out .= $outLine . "\n";
1135 # Closing open td, tr && table
1136 while ( count( $td_history ) > 0 ) {
1137 if ( array_pop( $td_history ) ) {
1140 if ( array_pop( $tr_history ) ) {
1143 if ( !array_pop( $has_opened_tr ) ) {
1144 $out .= "<tr><td></td></tr>\n";
1147 $out .= "</table>\n";
1150 # Remove trailing line-ending (b/c)
1151 if ( substr( $out, -1 ) === "\n" ) {
1152 $out = substr( $out, 0, -1 );
1155 # special case: don't return empty table
1156 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1160 wfProfileOut( __METHOD__
);
1166 * Helper function for parse() that transforms wiki markup into
1167 * HTML. Only called for $mOutputType == self::OT_HTML.
1171 * @param $text string
1172 * @param $isMain bool
1173 * @param $frame bool
1177 function internalParse( $text, $isMain = true, $frame = false ) {
1178 wfProfileIn( __METHOD__
);
1182 # Hook to suspend the parser in this state
1183 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1184 wfProfileOut( __METHOD__
);
1188 # if $frame is provided, then use $frame for replacing any variables
1190 # use frame depth to infer how include/noinclude tags should be handled
1191 # depth=0 means this is the top-level document; otherwise it's an included document
1192 if ( !$frame->depth
) {
1195 $flag = Parser
::PTD_FOR_INCLUSION
;
1197 $dom = $this->preprocessToDom( $text, $flag );
1198 $text = $frame->expand( $dom );
1200 # if $frame is not provided, then use old-style replaceVariables
1201 $text = $this->replaceVariables( $text );
1204 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1205 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1206 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1208 # Tables need to come after variable replacement for things to work
1209 # properly; putting them before other transformations should keep
1210 # exciting things like link expansions from showing up in surprising
1212 $text = $this->doTableStuff( $text );
1214 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1216 $text = $this->doDoubleUnderscore( $text );
1218 $text = $this->doHeadings( $text );
1219 $text = $this->replaceInternalLinks( $text );
1220 $text = $this->doAllQuotes( $text );
1221 $text = $this->replaceExternalLinks( $text );
1223 # replaceInternalLinks may sometimes leave behind
1224 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1225 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1227 $text = $this->doMagicLinks( $text );
1228 $text = $this->formatHeadings( $text, $origText, $isMain );
1230 wfProfileOut( __METHOD__
);
1235 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1236 * magic external links.
1241 * @param $text string
1245 function doMagicLinks( $text ) {
1246 wfProfileIn( __METHOD__
);
1247 $prots = wfUrlProtocolsWithoutProtRel();
1248 $urlChar = self
::EXT_LINK_URL_CLASS
;
1249 $text = preg_replace_callback(
1251 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1252 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1253 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1254 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1255 ISBN\s+(\b # m[5]: ISBN, capture number
1256 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1257 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1258 [0-9Xx] # check digit
1260 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1261 wfProfileOut( __METHOD__
);
1266 * @throws MWException
1268 * @return HTML|string
1270 function magicLinkCallback( $m ) {
1271 if ( isset( $m[1] ) && $m[1] !== '' ) {
1274 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1277 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1278 # Free external link
1279 return $this->makeFreeExternalLink( $m[0] );
1280 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1282 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1285 $CssClass = 'mw-magiclink-rfc';
1287 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1289 $urlmsg = 'pubmedurl';
1290 $CssClass = 'mw-magiclink-pmid';
1293 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1294 substr( $m[0], 0, 20 ) . '"' );
1296 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1297 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1298 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1301 $num = strtr( $isbn, array(
1306 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1307 return '<a href="' .
1308 htmlspecialchars( $titleObj->getLocalURL() ) .
1309 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1316 * Make a free external link, given a user-supplied URL
1318 * @param $url string
1320 * @return string HTML
1323 function makeFreeExternalLink( $url ) {
1324 wfProfileIn( __METHOD__
);
1328 # The characters '<' and '>' (which were escaped by
1329 # removeHTMLtags()) should not be included in
1330 # URLs, per RFC 2396.
1332 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1333 $trail = substr( $url, $m2[0][1] ) . $trail;
1334 $url = substr( $url, 0, $m2[0][1] );
1337 # Move trailing punctuation to $trail
1339 # If there is no left bracket, then consider right brackets fair game too
1340 if ( strpos( $url, '(' ) === false ) {
1344 $numSepChars = strspn( strrev( $url ), $sep );
1345 if ( $numSepChars ) {
1346 $trail = substr( $url, -$numSepChars ) . $trail;
1347 $url = substr( $url, 0, -$numSepChars );
1350 $url = Sanitizer
::cleanUrl( $url );
1352 # Is this an external image?
1353 $text = $this->maybeMakeExternalImage( $url );
1354 if ( $text === false ) {
1355 # Not an image, make a link
1356 $text = Linker
::makeExternalLink( $url,
1357 $this->getConverterLanguage()->markNoConversion( $url, true ),
1359 $this->getExternalLinkAttribs( $url ) );
1360 # Register it in the output object...
1361 # Replace unnecessary URL escape codes with their equivalent characters
1362 $pasteurized = self
::replaceUnusualEscapes( $url );
1363 $this->mOutput
->addExternalLink( $pasteurized );
1365 wfProfileOut( __METHOD__
);
1366 return $text . $trail;
1370 * Parse headers and return html
1374 * @param $text string
1378 function doHeadings( $text ) {
1379 wfProfileIn( __METHOD__
);
1380 for ( $i = 6; $i >= 1; --$i ) {
1381 $h = str_repeat( '=', $i );
1382 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1384 wfProfileOut( __METHOD__
);
1389 * Replace single quotes with HTML markup
1392 * @param $text string
1394 * @return string the altered text
1396 function doAllQuotes( $text ) {
1397 wfProfileIn( __METHOD__
);
1399 $lines = StringUtils
::explode( "\n", $text );
1400 foreach ( $lines as $line ) {
1401 $outtext .= $this->doQuotes( $line ) . "\n";
1403 $outtext = substr( $outtext, 0, -1 );
1404 wfProfileOut( __METHOD__
);
1409 * Helper function for doAllQuotes()
1411 * @param $text string
1415 public function doQuotes( $text ) {
1416 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1417 if ( count( $arr ) == 1 ) {
1420 # First, do some preliminary work. This may shift some apostrophes from
1421 # being mark-up to being text. It also counts the number of occurrences
1422 # of bold and italics mark-ups.
1425 for ( $i = 0; $i < count( $arr ); $i++
) {
1426 if ( ( $i %
2 ) == 1 ) {
1427 # If there are ever four apostrophes, assume the first is supposed to
1428 # be text, and the remaining three constitute mark-up for bold text.
1429 if ( strlen( $arr[$i] ) == 4 ) {
1430 $arr[$i - 1] .= "'";
1432 } elseif ( strlen( $arr[$i] ) > 5 ) {
1433 # If there are more than 5 apostrophes in a row, assume they're all
1434 # text except for the last 5.
1435 $arr[$i - 1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1438 # Count the number of occurrences of bold and italics mark-ups.
1439 # We are not counting sequences of five apostrophes.
1440 if ( strlen( $arr[$i] ) == 2 ) {
1442 } elseif ( strlen( $arr[$i] ) == 3 ) {
1444 } elseif ( strlen( $arr[$i] ) == 5 ) {
1451 # If there is an odd number of both bold and italics, it is likely
1452 # that one of the bold ones was meant to be an apostrophe followed
1453 # by italics. Which one we cannot know for certain, but it is more
1454 # likely to be one that has a single-letter word before it.
1455 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1457 $firstsingleletterword = -1;
1458 $firstmultiletterword = -1;
1460 foreach ( $arr as $r ) {
1461 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1462 $x1 = substr( $arr[$i - 1], -1 );
1463 $x2 = substr( $arr[$i - 1], -2, 1 );
1464 if ( $x1 === ' ' ) {
1465 if ( $firstspace == -1 ) {
1468 } elseif ( $x2 === ' ' ) {
1469 if ( $firstsingleletterword == -1 ) {
1470 $firstsingleletterword = $i;
1473 if ( $firstmultiletterword == -1 ) {
1474 $firstmultiletterword = $i;
1481 # If there is a single-letter word, use it!
1482 if ( $firstsingleletterword > -1 ) {
1483 $arr[$firstsingleletterword] = "''";
1484 $arr[$firstsingleletterword - 1] .= "'";
1485 } elseif ( $firstmultiletterword > -1 ) {
1486 # If not, but there's a multi-letter word, use that one.
1487 $arr[$firstmultiletterword] = "''";
1488 $arr[$firstmultiletterword - 1] .= "'";
1489 } elseif ( $firstspace > -1 ) {
1490 # ... otherwise use the first one that has neither.
1491 # (notice that it is possible for all three to be -1 if, for example,
1492 # there is only one pentuple-apostrophe in the line)
1493 $arr[$firstspace] = "''";
1494 $arr[$firstspace - 1] .= "'";
1498 # Now let's actually convert our apostrophic mush to HTML!
1503 foreach ( $arr as $r ) {
1504 if ( ( $i %
2 ) == 0 ) {
1505 if ( $state === 'both' ) {
1511 if ( strlen( $r ) == 2 ) {
1512 if ( $state === 'i' ) {
1515 } elseif ( $state === 'bi' ) {
1518 } elseif ( $state === 'ib' ) {
1519 $output .= '</b></i><b>';
1521 } elseif ( $state === 'both' ) {
1522 $output .= '<b><i>' . $buffer . '</i>';
1524 } else { # $state can be 'b' or ''
1528 } elseif ( strlen( $r ) == 3 ) {
1529 if ( $state === 'b' ) {
1532 } elseif ( $state === 'bi' ) {
1533 $output .= '</i></b><i>';
1535 } elseif ( $state === 'ib' ) {
1538 } elseif ( $state === 'both' ) {
1539 $output .= '<i><b>' . $buffer . '</b>';
1541 } else { # $state can be 'i' or ''
1545 } elseif ( strlen( $r ) == 5 ) {
1546 if ( $state === 'b' ) {
1547 $output .= '</b><i>';
1549 } elseif ( $state === 'i' ) {
1550 $output .= '</i><b>';
1552 } elseif ( $state === 'bi' ) {
1553 $output .= '</i></b>';
1555 } elseif ( $state === 'ib' ) {
1556 $output .= '</b></i>';
1558 } elseif ( $state === 'both' ) {
1559 $output .= '<i><b>' . $buffer . '</b></i>';
1561 } else { # ($state == '')
1569 # Now close all remaining tags. Notice that the order is important.
1570 if ( $state === 'b' ||
$state === 'ib' ) {
1573 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1576 if ( $state === 'bi' ) {
1579 # There might be lonely ''''', so make sure we have a buffer
1580 if ( $state === 'both' && $buffer ) {
1581 $output .= '<b><i>' . $buffer . '</i></b>';
1588 * Replace external links (REL)
1590 * Note: this is all very hackish and the order of execution matters a lot.
1591 * Make sure to run tests/parserTests.php if you change this code.
1595 * @param $text string
1597 * @throws MWException
1600 function replaceExternalLinks( $text ) {
1601 wfProfileIn( __METHOD__
);
1603 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1604 if ( $bits === false ) {
1605 wfProfileOut( __METHOD__
);
1606 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1608 $s = array_shift( $bits );
1611 while ( $i < count( $bits ) ) {
1614 $text = $bits[$i++
];
1615 $trail = $bits[$i++
];
1617 # The characters '<' and '>' (which were escaped by
1618 # removeHTMLtags()) should not be included in
1619 # URLs, per RFC 2396.
1621 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1622 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1623 $url = substr( $url, 0, $m2[0][1] );
1626 # If the link text is an image URL, replace it with an <img> tag
1627 # This happened by accident in the original parser, but some people used it extensively
1628 $img = $this->maybeMakeExternalImage( $text );
1629 if ( $img !== false ) {
1635 # Set linktype for CSS - if URL==text, link is essentially free
1636 $linktype = ( $text === $url ) ?
'free' : 'text';
1638 # No link text, e.g. [http://domain.tld/some.link]
1639 if ( $text == '' ) {
1641 $langObj = $this->getTargetLanguage();
1642 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1643 $linktype = 'autonumber';
1645 # Have link text, e.g. [http://domain.tld/some.link text]s
1647 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1650 $text = $this->getConverterLanguage()->markNoConversion( $text );
1652 $url = Sanitizer
::cleanUrl( $url );
1654 # Use the encoded URL
1655 # This means that users can paste URLs directly into the text
1656 # Funny characters like ö aren't valid in URLs anyway
1657 # This was changed in August 2004
1658 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1659 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1661 # Register link in the output object.
1662 # Replace unnecessary URL escape codes with the referenced character
1663 # This prevents spammers from hiding links from the filters
1664 $pasteurized = self
::replaceUnusualEscapes( $url );
1665 $this->mOutput
->addExternalLink( $pasteurized );
1668 wfProfileOut( __METHOD__
);
1672 * Get the rel attribute for a particular external link.
1675 * @param string|bool $url optional URL, to extract the domain from for rel =>
1676 * nofollow if appropriate
1677 * @param $title Title optional Title, for wgNoFollowNsExceptions lookups
1678 * @return string|null rel attribute for $url
1680 public static function getExternalLinkRel( $url = false, $title = null ) {
1681 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1682 $ns = $title ?
$title->getNamespace() : false;
1683 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1684 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1691 * Get an associative array of additional HTML attributes appropriate for a
1692 * particular external link. This currently may include rel => nofollow
1693 * (depending on configuration, namespace, and the URL's domain) and/or a
1694 * target attribute (depending on configuration).
1696 * @param string|bool $url optional URL, to extract the domain from for rel =>
1697 * nofollow if appropriate
1698 * @return Array associative array of HTML attributes
1700 function getExternalLinkAttribs( $url = false ) {
1702 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1704 if ( $this->mOptions
->getExternalLinkTarget() ) {
1705 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1711 * Replace unusual URL escape codes with their equivalent characters
1713 * @param $url String
1716 * @todo This can merge genuinely required bits in the path or query string,
1717 * breaking legit URLs. A proper fix would treat the various parts of
1718 * the URL differently; as a workaround, just use the output for
1719 * statistical records, not for actual linking/output.
1721 static function replaceUnusualEscapes( $url ) {
1722 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1723 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1727 * Callback function used in replaceUnusualEscapes().
1728 * Replaces unusual URL escape codes with their equivalent character
1730 * @param $matches array
1734 private static function replaceUnusualEscapesCallback( $matches ) {
1735 $char = urldecode( $matches[0] );
1736 $ord = ord( $char );
1737 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1738 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1739 # No, shouldn't be escaped
1742 # Yes, leave it escaped
1748 * make an image if it's allowed, either through the global
1749 * option, through the exception, or through the on-wiki whitelist
1752 * $param $url string
1756 function maybeMakeExternalImage( $url ) {
1757 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1758 $imagesexception = !empty( $imagesfrom );
1760 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1761 if ( $imagesexception && is_array( $imagesfrom ) ) {
1762 $imagematch = false;
1763 foreach ( $imagesfrom as $match ) {
1764 if ( strpos( $url, $match ) === 0 ) {
1769 } elseif ( $imagesexception ) {
1770 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1772 $imagematch = false;
1774 if ( $this->mOptions
->getAllowExternalImages()
1775 ||
( $imagesexception && $imagematch ) ) {
1776 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1778 $text = Linker
::makeExternalImage( $url );
1781 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1782 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1783 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1784 foreach ( $whitelist as $entry ) {
1785 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1786 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1789 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1790 # Image matches a whitelist entry
1791 $text = Linker
::makeExternalImage( $url );
1800 * Process [[ ]] wikilinks
1804 * @return String: processed text
1808 function replaceInternalLinks( $s ) {
1809 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1814 * Process [[ ]] wikilinks (RIL)
1816 * @throws MWException
1817 * @return LinkHolderArray
1821 function replaceInternalLinks2( &$s ) {
1822 wfProfileIn( __METHOD__
);
1824 wfProfileIn( __METHOD__
. '-setup' );
1825 static $tc = false, $e1, $e1_img;
1826 # the % is needed to support urlencoded titles as well
1828 $tc = Title
::legalChars() . '#%';
1829 # Match a link having the form [[namespace:link|alternate]]trail
1830 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1831 # Match cases where there is no "]]", which might still be images
1832 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1835 $holders = new LinkHolderArray( $this );
1837 # split the entire text string on occurrences of [[
1838 $a = StringUtils
::explode( '[[', ' ' . $s );
1839 # get the first element (all text up to first [[), and remove the space we added
1842 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1843 $s = substr( $s, 1 );
1845 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1847 if ( $useLinkPrefixExtension ) {
1848 # Match the end of a line for a word that's not followed by whitespace,
1849 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1850 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
1853 if ( is_null( $this->mTitle
) ) {
1854 wfProfileOut( __METHOD__
. '-setup' );
1855 wfProfileOut( __METHOD__
);
1856 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
1858 $nottalk = !$this->mTitle
->isTalkPage();
1860 if ( $useLinkPrefixExtension ) {
1862 if ( preg_match( $e2, $s, $m ) ) {
1863 $first_prefix = $m[2];
1865 $first_prefix = false;
1871 $useSubpages = $this->areSubpagesAllowed();
1872 wfProfileOut( __METHOD__
. '-setup' );
1874 # Loop for each link
1875 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
1876 # Check for excessive memory usage
1877 if ( $holders->isBig() ) {
1879 # Do the existence check, replace the link holders and clear the array
1880 $holders->replace( $s );
1884 if ( $useLinkPrefixExtension ) {
1885 wfProfileIn( __METHOD__
. '-prefixhandling' );
1886 if ( preg_match( $e2, $s, $m ) ) {
1893 if ( $first_prefix ) {
1894 $prefix = $first_prefix;
1895 $first_prefix = false;
1897 wfProfileOut( __METHOD__
. '-prefixhandling' );
1900 $might_be_img = false;
1902 wfProfileIn( __METHOD__
. "-e1" );
1903 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1905 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1906 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1907 # the real problem is with the $e1 regex
1910 # Still some problems for cases where the ] is meant to be outside punctuation,
1911 # and no image is in sight. See bug 2095.
1913 if ( $text !== '' &&
1914 substr( $m[3], 0, 1 ) === ']' &&
1915 strpos( $text, '[' ) !== false
1918 $text .= ']'; # so that replaceExternalLinks($text) works later
1919 $m[3] = substr( $m[3], 1 );
1921 # fix up urlencoded title texts
1922 if ( strpos( $m[1], '%' ) !== false ) {
1923 # Should anchors '#' also be rejected?
1924 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
1927 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1928 $might_be_img = true;
1930 if ( strpos( $m[1], '%' ) !== false ) {
1931 $m[1] = rawurldecode( $m[1] );
1934 } else { # Invalid form; output directly
1935 $s .= $prefix . '[[' . $line;
1936 wfProfileOut( __METHOD__
. "-e1" );
1939 wfProfileOut( __METHOD__
. "-e1" );
1940 wfProfileIn( __METHOD__
. "-misc" );
1942 # Don't allow internal links to pages containing
1943 # PROTO: where PROTO is a valid URL protocol; these
1944 # should be external links.
1945 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1946 $s .= $prefix . '[[' . $line;
1947 wfProfileOut( __METHOD__
. "-misc" );
1951 # Make subpage if necessary
1952 if ( $useSubpages ) {
1953 $link = $this->maybeDoSubpageLink( $m[1], $text );
1958 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1960 # Strip off leading ':'
1961 $link = substr( $link, 1 );
1964 wfProfileOut( __METHOD__
. "-misc" );
1965 wfProfileIn( __METHOD__
. "-title" );
1966 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1967 if ( $nt === null ) {
1968 $s .= $prefix . '[[' . $line;
1969 wfProfileOut( __METHOD__
. "-title" );
1973 $ns = $nt->getNamespace();
1974 $iw = $nt->getInterWiki();
1975 wfProfileOut( __METHOD__
. "-title" );
1977 if ( $might_be_img ) { # if this is actually an invalid link
1978 wfProfileIn( __METHOD__
. "-might_be_img" );
1979 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1982 # look at the next 'line' to see if we can close it there
1984 $next_line = $a->current();
1985 if ( $next_line === false ||
$next_line === null ) {
1988 $m = explode( ']]', $next_line, 3 );
1989 if ( count( $m ) == 3 ) {
1990 # the first ]] closes the inner link, the second the image
1992 $text .= "[[{$m[0]}]]{$m[1]}";
1995 } elseif ( count( $m ) == 2 ) {
1996 # if there's exactly one ]] that's fine, we'll keep looking
1997 $text .= "[[{$m[0]}]]{$m[1]}";
1999 # if $next_line is invalid too, we need look no further
2000 $text .= '[[' . $next_line;
2005 # we couldn't find the end of this imageLink, so output it raw
2006 # but don't ignore what might be perfectly normal links in the text we've examined
2007 $holders->merge( $this->replaceInternalLinks2( $text ) );
2008 $s .= "{$prefix}[[$link|$text";
2009 # note: no $trail, because without an end, there *is* no trail
2010 wfProfileOut( __METHOD__
. "-might_be_img" );
2013 } else { # it's not an image, so output it raw
2014 $s .= "{$prefix}[[$link|$text";
2015 # note: no $trail, because without an end, there *is* no trail
2016 wfProfileOut( __METHOD__
. "-might_be_img" );
2019 wfProfileOut( __METHOD__
. "-might_be_img" );
2022 $wasblank = ( $text == '' );
2026 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2027 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2028 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2029 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2030 $text = $this->doQuotes( $text );
2033 # Link not escaped by : , create the various objects
2036 wfProfileIn( __METHOD__
. "-interwiki" );
2037 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
2038 // XXX: the above check prevents links to sites with identifiers that are not language codes
2040 # Bug 24502: filter duplicates
2041 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2042 $this->mLangLinkLanguages
[$iw] = true;
2043 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2046 $s = rtrim( $s . $prefix );
2047 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2048 wfProfileOut( __METHOD__
. "-interwiki" );
2051 wfProfileOut( __METHOD__
. "-interwiki" );
2053 if ( $ns == NS_FILE
) {
2054 wfProfileIn( __METHOD__
. "-image" );
2055 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2057 # if no parameters were passed, $text
2058 # becomes something like "File:Foo.png",
2059 # which we don't want to pass on to the
2063 # recursively parse links inside the image caption
2064 # actually, this will parse them in any other parameters, too,
2065 # but it might be hard to fix that, and it doesn't matter ATM
2066 $text = $this->replaceExternalLinks( $text );
2067 $holders->merge( $this->replaceInternalLinks2( $text ) );
2069 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2070 $s .= $prefix . $this->armorLinks(
2071 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2073 $s .= $prefix . $trail;
2075 wfProfileOut( __METHOD__
. "-image" );
2079 if ( $ns == NS_CATEGORY
) {
2080 wfProfileIn( __METHOD__
. "-category" );
2081 $s = rtrim( $s . "\n" ); # bug 87
2084 $sortkey = $this->getDefaultSort();
2088 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2089 $sortkey = str_replace( "\n", '', $sortkey );
2090 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2091 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2094 * Strip the whitespace Category links produce, see bug 87
2095 * @todo We might want to use trim($tmp, "\n") here.
2097 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2099 wfProfileOut( __METHOD__
. "-category" );
2104 # Self-link checking
2105 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2106 if ( $nt->equals( $this->mTitle
) ||
( !$nt->isKnown() && in_array(
2107 $this->mTitle
->getPrefixedText(),
2108 $this->getConverterLanguage()->autoConvertToAllVariants( $nt->getPrefixedText() ),
2111 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2116 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2117 # @todo FIXME: Should do batch file existence checks, see comment below
2118 if ( $ns == NS_MEDIA
) {
2119 wfProfileIn( __METHOD__
. "-media" );
2120 # Give extensions a chance to select the file revision for us
2123 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2124 array( $this, $nt, &$options, &$descQuery ) );
2125 # Fetch and register the file (file title may be different via hooks)
2126 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2127 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2128 $s .= $prefix . $this->armorLinks(
2129 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2130 wfProfileOut( __METHOD__
. "-media" );
2134 wfProfileIn( __METHOD__
. "-always_known" );
2135 # Some titles, such as valid special pages or files in foreign repos, should
2136 # be shown as bluelinks even though they're not included in the page table
2138 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2139 # batch file existence checks for NS_FILE and NS_MEDIA
2140 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2141 $this->mOutput
->addLink( $nt );
2142 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2144 # Links will be added to the output link list after checking
2145 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2147 wfProfileOut( __METHOD__
. "-always_known" );
2149 wfProfileOut( __METHOD__
);
2154 * Render a forced-blue link inline; protect against double expansion of
2155 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2156 * Since this little disaster has to split off the trail text to avoid
2157 * breaking URLs in the following text without breaking trails on the
2158 * wiki links, it's been made into a horrible function.
2161 * @param $text String
2162 * @param array $query or String
2163 * @param $trail String
2164 * @param $prefix String
2165 * @return String: HTML-wikitext mix oh yuck
2167 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2168 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2170 if ( is_string( $query ) ) {
2171 $query = wfCgiToArray( $query );
2173 if ( $text == '' ) {
2174 $text = htmlspecialchars( $nt->getPrefixedText() );
2177 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2179 return $this->armorLinks( $link ) . $trail;
2183 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2184 * going to go through further parsing steps before inline URL expansion.
2186 * Not needed quite as much as it used to be since free links are a bit
2187 * more sensible these days. But bracketed links are still an issue.
2189 * @param string $text more-or-less HTML
2190 * @return String: less-or-more HTML with NOPARSE bits
2192 function armorLinks( $text ) {
2193 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2194 "{$this->mUniqPrefix}NOPARSE$1", $text );
2198 * Return true if subpage links should be expanded on this page.
2201 function areSubpagesAllowed() {
2202 # Some namespaces don't allow subpages
2203 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2207 * Handle link to subpage if necessary
2209 * @param string $target the source of the link
2210 * @param &$text String: the link text, modified as necessary
2211 * @return string the full name of the link
2214 function maybeDoSubpageLink( $target, &$text ) {
2215 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2219 * Used by doBlockLevels()
2224 function closeParagraph() {
2226 if ( $this->mLastSection
!= '' ) {
2227 $result = '</' . $this->mLastSection
. ">\n";
2229 $this->mInPre
= false;
2230 $this->mLastSection
= '';
2235 * getCommon() returns the length of the longest common substring
2236 * of both arguments, starting at the beginning of both.
2239 * @param $st1 string
2240 * @param $st2 string
2244 function getCommon( $st1, $st2 ) {
2245 $fl = strlen( $st1 );
2246 $shorter = strlen( $st2 );
2247 if ( $fl < $shorter ) {
2251 for ( $i = 0; $i < $shorter; ++
$i ) {
2252 if ( $st1[$i] != $st2[$i] ) {
2260 * These next three functions open, continue, and close the list
2261 * element appropriate to the prefix character passed into them.
2264 * @param $char string
2268 function openList( $char ) {
2269 $result = $this->closeParagraph();
2271 if ( '*' === $char ) {
2272 $result .= '<ul><li>';
2273 } elseif ( '#' === $char ) {
2274 $result .= '<ol><li>';
2275 } elseif ( ':' === $char ) {
2276 $result .= '<dl><dd>';
2277 } elseif ( ';' === $char ) {
2278 $result .= '<dl><dt>';
2279 $this->mDTopen
= true;
2281 $result = '<!-- ERR 1 -->';
2289 * @param $char String
2294 function nextItem( $char ) {
2295 if ( '*' === $char ||
'#' === $char ) {
2297 } elseif ( ':' === $char ||
';' === $char ) {
2299 if ( $this->mDTopen
) {
2302 if ( ';' === $char ) {
2303 $this->mDTopen
= true;
2304 return $close . '<dt>';
2306 $this->mDTopen
= false;
2307 return $close . '<dd>';
2310 return '<!-- ERR 2 -->';
2315 * @param $char String
2320 function closeList( $char ) {
2321 if ( '*' === $char ) {
2322 $text = '</li></ul>';
2323 } elseif ( '#' === $char ) {
2324 $text = '</li></ol>';
2325 } elseif ( ':' === $char ) {
2326 if ( $this->mDTopen
) {
2327 $this->mDTopen
= false;
2328 $text = '</dt></dl>';
2330 $text = '</dd></dl>';
2333 return '<!-- ERR 3 -->';
2335 return $text . "\n";
2340 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2342 * @param $text String
2343 * @param $linestart Boolean: whether or not this is at the start of a line.
2345 * @return string the lists rendered as HTML
2347 function doBlockLevels( $text, $linestart ) {
2348 wfProfileIn( __METHOD__
);
2350 # Parsing through the text line by line. The main thing
2351 # happening here is handling of block-level elements p, pre,
2352 # and making lists from lines starting with * # : etc.
2354 $textLines = StringUtils
::explode( "\n", $text );
2356 $lastPrefix = $output = '';
2357 $this->mDTopen
= $inBlockElem = false;
2359 $paragraphStack = false;
2361 foreach ( $textLines as $oLine ) {
2363 if ( !$linestart ) {
2373 $lastPrefixLength = strlen( $lastPrefix );
2374 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2375 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2376 # If not in a <pre> element, scan for and figure out what prefixes are there.
2377 if ( !$this->mInPre
) {
2378 # Multiple prefixes may abut each other for nested lists.
2379 $prefixLength = strspn( $oLine, '*#:;' );
2380 $prefix = substr( $oLine, 0, $prefixLength );
2383 # ; and : are both from definition-lists, so they're equivalent
2384 # for the purposes of determining whether or not we need to open/close
2386 $prefix2 = str_replace( ';', ':', $prefix );
2387 $t = substr( $oLine, $prefixLength );
2388 $this->mInPre
= (bool)$preOpenMatch;
2390 # Don't interpret any other prefixes in preformatted text
2392 $prefix = $prefix2 = '';
2397 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2398 # Same as the last item, so no need to deal with nesting or opening stuff
2399 $output .= $this->nextItem( substr( $prefix, -1 ) );
2400 $paragraphStack = false;
2402 if ( substr( $prefix, -1 ) === ';' ) {
2403 # The one nasty exception: definition lists work like this:
2404 # ; title : definition text
2405 # So we check for : in the remainder text to split up the
2406 # title and definition, without b0rking links.
2408 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2410 $output .= $term . $this->nextItem( ':' );
2413 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2414 # We need to open or close prefixes, or both.
2416 # Either open or close a level...
2417 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2418 $paragraphStack = false;
2420 # Close all the prefixes which aren't shared.
2421 while ( $commonPrefixLength < $lastPrefixLength ) {
2422 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2423 --$lastPrefixLength;
2426 # Continue the current prefix if appropriate.
2427 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2428 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2431 # Open prefixes where appropriate.
2432 while ( $prefixLength > $commonPrefixLength ) {
2433 $char = substr( $prefix, $commonPrefixLength, 1 );
2434 $output .= $this->openList( $char );
2436 if ( ';' === $char ) {
2437 # @todo FIXME: This is dupe of code above
2438 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2440 $output .= $term . $this->nextItem( ':' );
2443 ++
$commonPrefixLength;
2445 $lastPrefix = $prefix2;
2448 # If we have no prefixes, go to paragraph mode.
2449 if ( 0 == $prefixLength ) {
2450 wfProfileIn( __METHOD__
. "-paragraph" );
2451 # No prefix (not in list)--go to paragraph mode
2452 # XXX: use a stack for nestable elements like span, table and div
2453 $openmatch = preg_match( '/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2454 $closematch = preg_match(
2455 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|' .
2456 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|' . $this->mUniqPrefix
. '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', $t );
2457 if ( $openmatch or $closematch ) {
2458 $paragraphStack = false;
2459 # TODO bug 5718: paragraph closed
2460 $output .= $this->closeParagraph();
2461 if ( $preOpenMatch and !$preCloseMatch ) {
2462 $this->mInPre
= true;
2464 $inBlockElem = !$closematch;
2465 } elseif ( !$inBlockElem && !$this->mInPre
) {
2466 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2468 if ( $this->mLastSection
!== 'pre' ) {
2469 $paragraphStack = false;
2470 $output .= $this->closeParagraph() . '<pre>';
2471 $this->mLastSection
= 'pre';
2473 $t = substr( $t, 1 );
2476 if ( trim( $t ) === '' ) {
2477 if ( $paragraphStack ) {
2478 $output .= $paragraphStack . '<br />';
2479 $paragraphStack = false;
2480 $this->mLastSection
= 'p';
2482 if ( $this->mLastSection
!== 'p' ) {
2483 $output .= $this->closeParagraph();
2484 $this->mLastSection
= '';
2485 $paragraphStack = '<p>';
2487 $paragraphStack = '</p><p>';
2491 if ( $paragraphStack ) {
2492 $output .= $paragraphStack;
2493 $paragraphStack = false;
2494 $this->mLastSection
= 'p';
2495 } elseif ( $this->mLastSection
!== 'p' ) {
2496 $output .= $this->closeParagraph() . '<p>';
2497 $this->mLastSection
= 'p';
2502 wfProfileOut( __METHOD__
. "-paragraph" );
2504 # somewhere above we forget to get out of pre block (bug 785)
2505 if ( $preCloseMatch && $this->mInPre
) {
2506 $this->mInPre
= false;
2508 if ( $paragraphStack === false ) {
2509 $output .= $t . "\n";
2512 while ( $prefixLength ) {
2513 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2516 if ( $this->mLastSection
!= '' ) {
2517 $output .= '</' . $this->mLastSection
. '>';
2518 $this->mLastSection
= '';
2521 wfProfileOut( __METHOD__
);
2526 * Split up a string on ':', ignoring any occurrences inside tags
2527 * to prevent illegal overlapping.
2529 * @param string $str the string to split
2530 * @param &$before String set to everything before the ':'
2531 * @param &$after String set to everything after the ':'
2532 * @throws MWException
2533 * @return String the position of the ':', or false if none found
2535 function findColonNoLinks( $str, &$before, &$after ) {
2536 wfProfileIn( __METHOD__
);
2538 $pos = strpos( $str, ':' );
2539 if ( $pos === false ) {
2541 wfProfileOut( __METHOD__
);
2545 $lt = strpos( $str, '<' );
2546 if ( $lt === false ||
$lt > $pos ) {
2547 # Easy; no tag nesting to worry about
2548 $before = substr( $str, 0, $pos );
2549 $after = substr( $str, $pos +
1 );
2550 wfProfileOut( __METHOD__
);
2554 # Ugly state machine to walk through avoiding tags.
2555 $state = self
::COLON_STATE_TEXT
;
2557 $len = strlen( $str );
2558 for ( $i = 0; $i < $len; $i++
) {
2562 # (Using the number is a performance hack for common cases)
2563 case 0: # self::COLON_STATE_TEXT:
2566 # Could be either a <start> tag or an </end> tag
2567 $state = self
::COLON_STATE_TAGSTART
;
2570 if ( $stack == 0 ) {
2572 $before = substr( $str, 0, $i );
2573 $after = substr( $str, $i +
1 );
2574 wfProfileOut( __METHOD__
);
2577 # Embedded in a tag; don't break it.
2580 # Skip ahead looking for something interesting
2581 $colon = strpos( $str, ':', $i );
2582 if ( $colon === false ) {
2583 # Nothing else interesting
2584 wfProfileOut( __METHOD__
);
2587 $lt = strpos( $str, '<', $i );
2588 if ( $stack === 0 ) {
2589 if ( $lt === false ||
$colon < $lt ) {
2591 $before = substr( $str, 0, $colon );
2592 $after = substr( $str, $colon +
1 );
2593 wfProfileOut( __METHOD__
);
2597 if ( $lt === false ) {
2598 # Nothing else interesting to find; abort!
2599 # We're nested, but there's no close tags left. Abort!
2602 # Skip ahead to next tag start
2604 $state = self
::COLON_STATE_TAGSTART
;
2607 case 1: # self::COLON_STATE_TAG:
2612 $state = self
::COLON_STATE_TEXT
;
2615 # Slash may be followed by >?
2616 $state = self
::COLON_STATE_TAGSLASH
;
2622 case 2: # self::COLON_STATE_TAGSTART:
2625 $state = self
::COLON_STATE_CLOSETAG
;
2628 $state = self
::COLON_STATE_COMMENT
;
2631 # Illegal early close? This shouldn't happen D:
2632 $state = self
::COLON_STATE_TEXT
;
2635 $state = self
::COLON_STATE_TAG
;
2638 case 3: # self::COLON_STATE_CLOSETAG:
2643 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2644 wfProfileOut( __METHOD__
);
2647 $state = self
::COLON_STATE_TEXT
;
2650 case self
::COLON_STATE_TAGSLASH
:
2652 # Yes, a self-closed tag <blah/>
2653 $state = self
::COLON_STATE_TEXT
;
2655 # Probably we're jumping the gun, and this is an attribute
2656 $state = self
::COLON_STATE_TAG
;
2659 case 5: # self::COLON_STATE_COMMENT:
2661 $state = self
::COLON_STATE_COMMENTDASH
;
2664 case self
::COLON_STATE_COMMENTDASH
:
2666 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2668 $state = self
::COLON_STATE_COMMENT
;
2671 case self
::COLON_STATE_COMMENTDASHDASH
:
2673 $state = self
::COLON_STATE_TEXT
;
2675 $state = self
::COLON_STATE_COMMENT
;
2679 wfProfileOut( __METHOD__
);
2680 throw new MWException( "State machine error in " . __METHOD__
);
2684 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2685 wfProfileOut( __METHOD__
);
2688 wfProfileOut( __METHOD__
);
2693 * Return value of a magic variable (like PAGENAME)
2697 * @param $index integer
2698 * @param bool|\PPFrame $frame
2700 * @throws MWException
2703 function getVariableValue( $index, $frame = false ) {
2704 global $wgContLang, $wgSitename, $wgServer;
2705 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2707 if ( is_null( $this->mTitle
) ) {
2708 // If no title set, bad things are going to happen
2709 // later. Title should always be set since this
2710 // should only be called in the middle of a parse
2711 // operation (but the unit-tests do funky stuff)
2712 throw new MWException( __METHOD__
. ' Should only be '
2713 . ' called while parsing (no title set)' );
2717 * Some of these require message or data lookups and can be
2718 * expensive to check many times.
2720 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2721 if ( isset( $this->mVarCache
[$index] ) ) {
2722 return $this->mVarCache
[$index];
2726 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2727 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2729 $pageLang = $this->getFunctionLang();
2732 case 'currentmonth':
2733 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2735 case 'currentmonth1':
2736 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2738 case 'currentmonthname':
2739 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2741 case 'currentmonthnamegen':
2742 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2744 case 'currentmonthabbrev':
2745 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2748 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2751 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2754 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2757 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2759 case 'localmonthname':
2760 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2762 case 'localmonthnamegen':
2763 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2765 case 'localmonthabbrev':
2766 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2769 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2772 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2775 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2778 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2780 case 'fullpagename':
2781 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2783 case 'fullpagenamee':
2784 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2787 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2789 case 'subpagenamee':
2790 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2792 case 'rootpagename':
2793 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2795 case 'rootpagenamee':
2796 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getRootText() ) ) );
2798 case 'basepagename':
2799 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2801 case 'basepagenamee':
2802 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2804 case 'talkpagename':
2805 if ( $this->mTitle
->canTalk() ) {
2806 $talkPage = $this->mTitle
->getTalkPage();
2807 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2812 case 'talkpagenamee':
2813 if ( $this->mTitle
->canTalk() ) {
2814 $talkPage = $this->mTitle
->getTalkPage();
2815 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2820 case 'subjectpagename':
2821 $subjPage = $this->mTitle
->getSubjectPage();
2822 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2824 case 'subjectpagenamee':
2825 $subjPage = $this->mTitle
->getSubjectPage();
2826 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2828 case 'pageid': // requested in bug 23427
2829 $pageid = $this->getTitle()->getArticleID();
2830 if ( $pageid == 0 ) {
2831 # 0 means the page doesn't exist in the database,
2832 # which means the user is previewing a new page.
2833 # The vary-revision flag must be set, because the magic word
2834 # will have a different value once the page is saved.
2835 $this->mOutput
->setFlag( 'vary-revision' );
2836 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2838 $value = $pageid ?
$pageid : null;
2841 # Let the edit saving system know we should parse the page
2842 # *after* a revision ID has been assigned.
2843 $this->mOutput
->setFlag( 'vary-revision' );
2844 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2845 $value = $this->mRevisionId
;
2848 # Let the edit saving system know we should parse the page
2849 # *after* a revision ID has been assigned. This is for null edits.
2850 $this->mOutput
->setFlag( 'vary-revision' );
2851 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2852 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2854 case 'revisionday2':
2855 # Let the edit saving system know we should parse the page
2856 # *after* a revision ID has been assigned. This is for null edits.
2857 $this->mOutput
->setFlag( 'vary-revision' );
2858 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2859 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2861 case 'revisionmonth':
2862 # Let the edit saving system know we should parse the page
2863 # *after* a revision ID has been assigned. This is for null edits.
2864 $this->mOutput
->setFlag( 'vary-revision' );
2865 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2866 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2868 case 'revisionmonth1':
2869 # Let the edit saving system know we should parse the page
2870 # *after* a revision ID has been assigned. This is for null edits.
2871 $this->mOutput
->setFlag( 'vary-revision' );
2872 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2873 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2875 case 'revisionyear':
2876 # Let the edit saving system know we should parse the page
2877 # *after* a revision ID has been assigned. This is for null edits.
2878 $this->mOutput
->setFlag( 'vary-revision' );
2879 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2880 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2882 case 'revisiontimestamp':
2883 # Let the edit saving system know we should parse the page
2884 # *after* a revision ID has been assigned. This is for null edits.
2885 $this->mOutput
->setFlag( 'vary-revision' );
2886 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2887 $value = $this->getRevisionTimestamp();
2889 case 'revisionuser':
2890 # Let the edit saving system know we should parse the page
2891 # *after* a revision ID has been assigned. This is for null edits.
2892 $this->mOutput
->setFlag( 'vary-revision' );
2893 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2894 $value = $this->getRevisionUser();
2897 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2900 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2902 case 'namespacenumber':
2903 $value = $this->mTitle
->getNamespace();
2906 $value = $this->mTitle
->canTalk() ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() ) : '';
2909 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2911 case 'subjectspace':
2912 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2914 case 'subjectspacee':
2915 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2917 case 'currentdayname':
2918 $value = $pageLang->getWeekdayName( MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2921 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2924 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2927 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2930 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2931 # int to remove the padding
2932 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2935 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2937 case 'localdayname':
2938 $value = $pageLang->getWeekdayName( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1 );
2941 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2944 $value = $pageLang->time( MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ), false, false );
2947 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2950 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2951 # int to remove the padding
2952 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2955 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2957 case 'numberofarticles':
2958 $value = $pageLang->formatNum( SiteStats
::articles() );
2960 case 'numberoffiles':
2961 $value = $pageLang->formatNum( SiteStats
::images() );
2963 case 'numberofusers':
2964 $value = $pageLang->formatNum( SiteStats
::users() );
2966 case 'numberofactiveusers':
2967 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2969 case 'numberofpages':
2970 $value = $pageLang->formatNum( SiteStats
::pages() );
2972 case 'numberofadmins':
2973 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2975 case 'numberofedits':
2976 $value = $pageLang->formatNum( SiteStats
::edits() );
2978 case 'numberofviews':
2979 global $wgDisableCounters;
2980 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2982 case 'currenttimestamp':
2983 $value = wfTimestamp( TS_MW
, $ts );
2985 case 'localtimestamp':
2986 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2988 case 'currentversion':
2989 $value = SpecialVersion
::getVersion();
2992 return $wgArticlePath;
2998 $serverParts = wfParseUrl( $wgServer );
2999 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
3001 return $wgScriptPath;
3003 return $wgStylePath;
3004 case 'directionmark':
3005 return $pageLang->getDirMark();
3006 case 'contentlanguage':
3007 global $wgLanguageCode;
3008 return $wgLanguageCode;
3011 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
3019 $this->mVarCache
[$index] = $value;
3026 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3030 function initialiseVariables() {
3031 wfProfileIn( __METHOD__
);
3032 $variableIDs = MagicWord
::getVariableIDs();
3033 $substIDs = MagicWord
::getSubstIDs();
3035 $this->mVariables
= new MagicWordArray( $variableIDs );
3036 $this->mSubstWords
= new MagicWordArray( $substIDs );
3037 wfProfileOut( __METHOD__
);
3041 * Preprocess some wikitext and return the document tree.
3042 * This is the ghost of replace_variables().
3044 * @param string $text The text to parse
3045 * @param $flags Integer: bitwise combination of:
3046 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
3047 * included. Default is to assume a direct page view.
3049 * The generated DOM tree must depend only on the input text and the flags.
3050 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3052 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3053 * change in the DOM tree for a given text, must be passed through the section identifier
3054 * in the section edit link and thus back to extractSections().
3056 * The output of this function is currently only cached in process memory, but a persistent
3057 * cache may be implemented at a later date which takes further advantage of these strict
3058 * dependency requirements.
3064 function preprocessToDom( $text, $flags = 0 ) {
3065 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3070 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3076 public static function splitWhitespace( $s ) {
3077 $ltrimmed = ltrim( $s );
3078 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3079 $trimmed = rtrim( $ltrimmed );
3080 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3082 $w2 = substr( $ltrimmed, -$diff );
3086 return array( $w1, $trimmed, $w2 );
3090 * Replace magic variables, templates, and template arguments
3091 * with the appropriate text. Templates are substituted recursively,
3092 * taking care to avoid infinite loops.
3094 * Note that the substitution depends on value of $mOutputType:
3095 * self::OT_WIKI: only {{subst:}} templates
3096 * self::OT_PREPROCESS: templates but not extension tags
3097 * self::OT_HTML: all templates and extension tags
3099 * @param string $text the text to transform
3100 * @param $frame PPFrame Object describing the arguments passed to the template.
3101 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3102 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3103 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3108 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3109 # Is there any text? Also, Prevent too big inclusions!
3110 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3113 wfProfileIn( __METHOD__
);
3115 if ( $frame === false ) {
3116 $frame = $this->getPreprocessor()->newFrame();
3117 } elseif ( !( $frame instanceof PPFrame
) ) {
3118 wfDebug( __METHOD__
. " called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3119 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3122 $dom = $this->preprocessToDom( $text );
3123 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3124 $text = $frame->expand( $dom, $flags );
3126 wfProfileOut( __METHOD__
);
3131 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3133 * @param $args array
3137 static function createAssocArgs( $args ) {
3138 $assocArgs = array();
3140 foreach ( $args as $arg ) {
3141 $eqpos = strpos( $arg, '=' );
3142 if ( $eqpos === false ) {
3143 $assocArgs[$index++
] = $arg;
3145 $name = trim( substr( $arg, 0, $eqpos ) );
3146 $value = trim( substr( $arg, $eqpos +
1 ) );
3147 if ( $value === false ) {
3150 if ( $name !== false ) {
3151 $assocArgs[$name] = $value;
3160 * Warn the user when a parser limitation is reached
3161 * Will warn at most once the user per limitation type
3163 * @param string $limitationType should be one of:
3164 * 'expensive-parserfunction' (corresponding messages:
3165 * 'expensive-parserfunction-warning',
3166 * 'expensive-parserfunction-category')
3167 * 'post-expand-template-argument' (corresponding messages:
3168 * 'post-expand-template-argument-warning',
3169 * 'post-expand-template-argument-category')
3170 * 'post-expand-template-inclusion' (corresponding messages:
3171 * 'post-expand-template-inclusion-warning',
3172 * 'post-expand-template-inclusion-category')
3173 * @param int|null $current Current value
3174 * @param int|null $max Maximum allowed, when an explicit limit has been
3175 * exceeded, provide the values (optional)
3177 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3178 # does no harm if $current and $max are present but are unnecessary for the message
3179 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3180 ->inContentLanguage()->escaped();
3181 $this->mOutput
->addWarning( $warning );
3182 $this->addTrackingCategory( "$limitationType-category" );
3186 * Return the text of a template, after recursively
3187 * replacing any variables or templates within the template.
3189 * @param array $piece the parts of the template
3190 * $piece['title']: the title, i.e. the part before the |
3191 * $piece['parts']: the parameter array
3192 * $piece['lineStart']: whether the brace was at the start of a line
3193 * @param $frame PPFrame The current frame, contains template arguments
3194 * @throws MWException
3195 * @return String: the text of the template
3198 function braceSubstitution( $piece, $frame ) {
3199 wfProfileIn( __METHOD__
);
3200 wfProfileIn( __METHOD__
. '-setup' );
3203 $found = false; # $text has been filled
3204 $nowiki = false; # wiki markup in $text should be escaped
3205 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3206 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3207 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3208 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3210 # Title object, where $text came from
3213 # $part1 is the bit before the first |, and must contain only title characters.
3214 # Various prefixes will be stripped from it later.
3215 $titleWithSpaces = $frame->expand( $piece['title'] );
3216 $part1 = trim( $titleWithSpaces );
3219 # Original title text preserved for various purposes
3220 $originalTitle = $part1;
3222 # $args is a list of argument nodes, starting from index 0, not including $part1
3223 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3224 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3225 wfProfileOut( __METHOD__
. '-setup' );
3227 $titleProfileIn = null; // profile templates
3230 wfProfileIn( __METHOD__
. '-modifiers' );
3233 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3235 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3236 # Decide whether to expand template or keep wikitext as-is.
3237 if ( $this->ot
['wiki'] ) {
3238 if ( $substMatch === false ) {
3239 $literal = true; # literal when in PST with no prefix
3241 $literal = false; # expand when in PST with subst: or safesubst:
3244 if ( $substMatch == 'subst' ) {
3245 $literal = true; # literal when not in PST with plain subst:
3247 $literal = false; # expand when not in PST with safesubst: or no prefix
3251 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3258 if ( !$found && $args->getLength() == 0 ) {
3259 $id = $this->mVariables
->matchStartToEnd( $part1 );
3260 if ( $id !== false ) {
3261 $text = $this->getVariableValue( $id, $frame );
3262 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3263 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3269 # MSG, MSGNW and RAW
3272 $mwMsgnw = MagicWord
::get( 'msgnw' );
3273 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3276 # Remove obsolete MSG:
3277 $mwMsg = MagicWord
::get( 'msg' );
3278 $mwMsg->matchStartAndRemove( $part1 );
3282 $mwRaw = MagicWord
::get( 'raw' );
3283 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3284 $forceRawInterwiki = true;
3287 wfProfileOut( __METHOD__
. '-modifiers' );
3291 wfProfileIn( __METHOD__
. '-pfunc' );
3293 $colonPos = strpos( $part1, ':' );
3294 if ( $colonPos !== false ) {
3295 $func = substr( $part1, 0, $colonPos );
3296 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3297 for ( $i = 0; $i < $args->getLength(); $i++
) {
3298 $funcArgs[] = $args->item( $i );
3301 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3302 } catch ( Exception
$ex ) {
3303 wfProfileOut( __METHOD__
. '-pfunc' );
3304 wfProfileOut( __METHOD__
);
3308 # The interface for parser functions allows for extracting
3309 # flags into the local scope. Extract any forwarded flags
3313 wfProfileOut( __METHOD__
. '-pfunc' );
3316 # Finish mangling title and then check for loops.
3317 # Set $title to a Title object and $titleText to the PDBK
3320 # Split the title into page and subpage
3322 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3323 if ( $part1 !== $relative ) {
3325 $ns = $this->mTitle
->getNamespace();
3327 $title = Title
::newFromText( $part1, $ns );
3329 $titleText = $title->getPrefixedText();
3330 # Check for language variants if the template is not found
3331 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3332 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3334 # Do recursion depth check
3335 $limit = $this->mOptions
->getMaxTemplateDepth();
3336 if ( $frame->depth
>= $limit ) {
3338 $text = '<span class="error">'
3339 . wfMessage( 'parser-template-recursion-depth-warning' )
3340 ->numParams( $limit )->inContentLanguage()->text()
3346 # Load from database
3347 if ( !$found && $title ) {
3348 if ( !Profiler
::instance()->isPersistent() ) {
3349 # Too many unique items can kill profiling DBs/collectors
3350 $titleProfileIn = __METHOD__
. "-title-" . $title->getPrefixedDBkey();
3351 wfProfileIn( $titleProfileIn ); // template in
3353 wfProfileIn( __METHOD__
. '-loadtpl' );
3354 if ( !$title->isExternal() ) {
3355 if ( $title->isSpecialPage()
3356 && $this->mOptions
->getAllowSpecialInclusion()
3357 && $this->ot
['html'] )
3359 // Pass the template arguments as URL parameters.
3360 // "uselang" will have no effect since the Language object
3361 // is forced to the one defined in ParserOptions.
3362 $pageArgs = array();
3363 for ( $i = 0; $i < $args->getLength(); $i++
) {
3364 $bits = $args->item( $i )->splitArg();
3365 if ( strval( $bits['index'] ) === '' ) {
3366 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3367 $value = trim( $frame->expand( $bits['value'] ) );
3368 $pageArgs[$name] = $value;
3372 // Create a new context to execute the special page
3373 $context = new RequestContext
;
3374 $context->setTitle( $title );
3375 $context->setRequest( new FauxRequest( $pageArgs ) );
3376 $context->setUser( $this->getUser() );
3377 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3378 $ret = SpecialPageFactory
::capturePath( $title, $context );
3380 $text = $context->getOutput()->getHTML();
3381 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3384 $this->disableCache();
3386 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3387 $found = false; # access denied
3388 wfDebug( __METHOD__
. ": template inclusion denied for " . $title->getPrefixedDBkey() );
3390 list( $text, $title ) = $this->getTemplateDom( $title );
3391 if ( $text !== false ) {
3397 # If the title is valid but undisplayable, make a link to it
3398 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3399 $text = "[[:$titleText]]";
3402 } elseif ( $title->isTrans() ) {
3403 # Interwiki transclusion
3404 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3405 $text = $this->interwikiTransclude( $title, 'render' );
3408 $text = $this->interwikiTransclude( $title, 'raw' );
3409 # Preprocess it like a template
3410 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3416 # Do infinite loop check
3417 # This has to be done after redirect resolution to avoid infinite loops via redirects
3418 if ( !$frame->loopCheck( $title ) ) {
3420 $text = '<span class="error">'
3421 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3423 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3425 wfProfileOut( __METHOD__
. '-loadtpl' );
3428 # If we haven't found text to substitute by now, we're done
3429 # Recover the source wikitext and return it
3431 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3432 if ( $titleProfileIn ) {
3433 wfProfileOut( $titleProfileIn ); // template out
3435 wfProfileOut( __METHOD__
);
3436 return array( 'object' => $text );
3439 # Expand DOM-style return values in a child frame
3440 if ( $isChildObj ) {
3441 # Clean up argument array
3442 $newFrame = $frame->newChild( $args, $title );
3445 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3446 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3447 # Expansion is eligible for the empty-frame cache
3448 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3449 $text = $this->mTplExpandCache
[$titleText];
3451 $text = $newFrame->expand( $text );
3452 $this->mTplExpandCache
[$titleText] = $text;
3455 # Uncached expansion
3456 $text = $newFrame->expand( $text );
3459 if ( $isLocalObj && $nowiki ) {
3460 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3461 $isLocalObj = false;
3464 if ( $titleProfileIn ) {
3465 wfProfileOut( $titleProfileIn ); // template out
3468 # Replace raw HTML by a placeholder
3470 $text = $this->insertStripItem( $text );
3471 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3472 # Escape nowiki-style return values
3473 $text = wfEscapeWikiText( $text );
3474 } elseif ( is_string( $text )
3475 && !$piece['lineStart']
3476 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3478 # Bug 529: if the template begins with a table or block-level
3479 # element, it should be treated as beginning a new line.
3480 # This behavior is somewhat controversial.
3481 $text = "\n" . $text;
3484 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3485 # Error, oversize inclusion
3486 if ( $titleText !== false ) {
3487 # Make a working, properly escaped link if possible (bug 23588)
3488 $text = "[[:$titleText]]";
3490 # This will probably not be a working link, but at least it may
3491 # provide some hint of where the problem is
3492 preg_replace( '/^:/', '', $originalTitle );
3493 $text = "[[:$originalTitle]]";
3495 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3496 $this->limitationWarn( 'post-expand-template-inclusion' );
3499 if ( $isLocalObj ) {
3500 $ret = array( 'object' => $text );
3502 $ret = array( 'text' => $text );
3505 wfProfileOut( __METHOD__
);
3510 * Call a parser function and return an array with text and flags.
3512 * The returned array will always contain a boolean 'found', indicating
3513 * whether the parser function was found or not. It may also contain the
3515 * text: string|object, resulting wikitext or PP DOM object
3516 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3517 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3518 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3519 * nowiki: bool, wiki markup in $text should be escaped
3522 * @param $frame PPFrame The current frame, contains template arguments
3523 * @param $function string Function name
3524 * @param $args array Arguments to the function
3527 public function callParserFunction( $frame, $function, array $args = array() ) {
3530 wfProfileIn( __METHOD__
);
3532 # Case sensitive functions
3533 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3534 $function = $this->mFunctionSynonyms
[1][$function];
3536 # Case insensitive functions
3537 $function = $wgContLang->lc( $function );
3538 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3539 $function = $this->mFunctionSynonyms
[0][$function];
3541 wfProfileOut( __METHOD__
);
3542 return array( 'found' => false );
3546 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3547 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3549 # Workaround for PHP bug 35229 and similar
3550 if ( !is_callable( $callback ) ) {
3551 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3552 wfProfileOut( __METHOD__
);
3553 throw new MWException( "Tag hook for $function is not callable\n" );
3556 $allArgs = array( &$this );
3557 if ( $flags & SFH_OBJECT_ARGS
) {
3558 # Convert arguments to PPNodes and collect for appending to $allArgs
3559 $funcArgs = array();
3560 foreach ( $args as $k => $v ) {
3561 if ( $v instanceof PPNode ||
$k === 0 ) {
3564 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3568 # Add a frame parameter, and pass the arguments as an array
3569 $allArgs[] = $frame;
3570 $allArgs[] = $funcArgs;
3572 # Convert arguments to plain text and append to $allArgs
3573 foreach ( $args as $k => $v ) {
3574 if ( $v instanceof PPNode
) {
3575 $allArgs[] = trim( $frame->expand( $v ) );
3576 } elseif ( is_int( $k ) && $k >= 0 ) {
3577 $allArgs[] = trim( $v );
3579 $allArgs[] = trim( "$k=$v" );
3584 $result = call_user_func_array( $callback, $allArgs );
3586 # The interface for function hooks allows them to return a wikitext
3587 # string or an array containing the string and any flags. This mungs
3588 # things around to match what this method should return.
3589 if ( !is_array( $result ) ) {
3595 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3596 $result['text'] = $result[0];
3598 unset( $result[0] );
3605 $preprocessFlags = 0;
3606 if ( isset( $result['noparse'] ) ) {
3607 $noparse = $result['noparse'];
3609 if ( isset( $result['preprocessFlags'] ) ) {
3610 $preprocessFlags = $result['preprocessFlags'];
3614 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3615 $result['isChildObj'] = true;
3617 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3618 wfProfileOut( __METHOD__
);
3624 * Get the semi-parsed DOM representation of a template with a given title,
3625 * and its redirect destination title. Cached.
3627 * @param $title Title
3631 function getTemplateDom( $title ) {
3632 $cacheTitle = $title;
3633 $titleText = $title->getPrefixedDBkey();
3635 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3636 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3637 $title = Title
::makeTitle( $ns, $dbk );
3638 $titleText = $title->getPrefixedDBkey();
3640 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3641 return array( $this->mTplDomCache
[$titleText], $title );
3644 # Cache miss, go to the database
3645 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3647 if ( $text === false ) {
3648 $this->mTplDomCache
[$titleText] = false;
3649 return array( false, $title );
3652 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3653 $this->mTplDomCache
[$titleText] = $dom;
3655 if ( !$title->equals( $cacheTitle ) ) {
3656 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3657 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3660 return array( $dom, $title );
3664 * Fetch the unparsed text of a template and register a reference to it.
3665 * @param Title $title
3666 * @return Array ( string or false, Title )
3668 function fetchTemplateAndTitle( $title ) {
3669 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3670 $stuff = call_user_func( $templateCb, $title, $this );
3671 $text = $stuff['text'];
3672 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3673 if ( isset( $stuff['deps'] ) ) {
3674 foreach ( $stuff['deps'] as $dep ) {
3675 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3676 if ( $dep['title']->equals( $this->getTitle() ) ) {
3677 // If we transclude ourselves, the final result
3678 // will change based on the new version of the page
3679 $this->mOutput
->setFlag( 'vary-revision' );
3683 return array( $text, $finalTitle );
3687 * Fetch the unparsed text of a template and register a reference to it.
3688 * @param Title $title
3689 * @return mixed string or false
3691 function fetchTemplate( $title ) {
3692 $rv = $this->fetchTemplateAndTitle( $title );
3697 * Static function to get a template
3698 * Can be overridden via ParserOptions::setTemplateCallback().
3700 * @param $title Title
3701 * @param $parser Parser
3705 static function statelessFetchTemplate( $title, $parser = false ) {
3706 $text = $skip = false;
3707 $finalTitle = $title;
3710 # Loop to fetch the article, with up to 1 redirect
3711 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3712 # Give extensions a chance to select the revision instead
3713 $id = false; # Assume current
3714 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3715 array( $parser, $title, &$skip, &$id ) );
3721 'page_id' => $title->getArticleID(),
3728 ? Revision
::newFromId( $id )
3729 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3730 $rev_id = $rev ?
$rev->getId() : 0;
3731 # If there is no current revision, there is no page
3732 if ( $id === false && !$rev ) {
3733 $linkCache = LinkCache
::singleton();
3734 $linkCache->addBadLinkObj( $title );
3739 'page_id' => $title->getArticleID(),
3740 'rev_id' => $rev_id );
3741 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3742 # We fetched a rev from a different title; register it too...
3744 'title' => $rev->getTitle(),
3745 'page_id' => $rev->getPage(),
3746 'rev_id' => $rev_id );
3750 $content = $rev->getContent();
3751 $text = $content ?
$content->getWikitextForTransclusion() : null;
3753 if ( $text === false ||
$text === null ) {
3757 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3759 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3760 if ( !$message->exists() ) {
3764 $content = $message->content();
3765 $text = $message->plain();
3773 $finalTitle = $title;
3774 $title = $content->getRedirectTarget();
3778 'finalTitle' => $finalTitle,
3783 * Fetch a file and its title and register a reference to it.
3784 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3785 * @param Title $title
3786 * @param array $options Array of options to RepoGroup::findFile
3789 function fetchFile( $title, $options = array() ) {
3790 $res = $this->fetchFileAndTitle( $title, $options );
3795 * Fetch a file and its title and register a reference to it.
3796 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3797 * @param Title $title
3798 * @param array $options Array of options to RepoGroup::findFile
3799 * @return Array ( File or false, Title of file )
3801 function fetchFileAndTitle( $title, $options = array() ) {
3802 $file = $this->fetchFileNoRegister( $title, $options );
3804 $time = $file ?
$file->getTimestamp() : false;
3805 $sha1 = $file ?
$file->getSha1() : false;
3806 # Register the file as a dependency...
3807 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3808 if ( $file && !$title->equals( $file->getTitle() ) ) {
3809 # Update fetched file title
3810 $title = $file->getTitle();
3811 if ( is_null( $file->getRedirectedTitle() ) ) {
3812 # This file was not a redirect, but the title does not match.
3813 # Register under the new name because otherwise the link will
3815 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3818 return array( $file, $title );
3822 * Helper function for fetchFileAndTitle.
3824 * Also useful if you need to fetch a file but not use it yet,
3825 * for example to get the file's handler.
3827 * @param Title $title
3828 * @param array $options Array of options to RepoGroup::findFile
3829 * @return File or false
3831 protected function fetchFileNoRegister( $title, $options = array() ) {
3832 if ( isset( $options['broken'] ) ) {
3833 $file = false; // broken thumbnail forced by hook
3834 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3835 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3836 } else { // get by (name,timestamp)
3837 $file = wfFindFile( $title, $options );
3843 * Transclude an interwiki link.
3845 * @param $title Title
3850 function interwikiTransclude( $title, $action ) {
3851 global $wgEnableScaryTranscluding;
3853 if ( !$wgEnableScaryTranscluding ) {
3854 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3857 $url = $title->getFullURL( array( 'action' => $action ) );
3859 if ( strlen( $url ) > 255 ) {
3860 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3862 return $this->fetchScaryTemplateMaybeFromCache( $url );
3866 * @param $url string
3867 * @return Mixed|String
3869 function fetchScaryTemplateMaybeFromCache( $url ) {
3870 global $wgTranscludeCacheExpiry;
3871 $dbr = wfGetDB( DB_SLAVE
);
3872 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3873 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
3874 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3876 return $obj->tc_contents
;
3879 $req = MWHttpRequest
::factory( $url );
3880 $status = $req->execute(); // Status object
3881 if ( $status->isOK() ) {
3882 $text = $req->getContent();
3883 } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
3884 return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3886 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3889 $dbw = wfGetDB( DB_MASTER
);
3890 $dbw->replace( 'transcache', array( 'tc_url' ), array(
3892 'tc_time' => $dbw->timestamp( time() ),
3893 'tc_contents' => $text
3899 * Triple brace replacement -- used for template arguments
3902 * @param $piece array
3903 * @param $frame PPFrame
3907 function argSubstitution( $piece, $frame ) {
3908 wfProfileIn( __METHOD__
);
3911 $parts = $piece['parts'];
3912 $nameWithSpaces = $frame->expand( $piece['title'] );
3913 $argName = trim( $nameWithSpaces );
3915 $text = $frame->getArgument( $argName );
3916 if ( $text === false && $parts->getLength() > 0
3920 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3923 # No match in frame, use the supplied default
3924 $object = $parts->item( 0 )->getChildren();
3926 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3927 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3928 $this->limitationWarn( 'post-expand-template-argument' );
3931 if ( $text === false && $object === false ) {
3933 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3935 if ( $error !== false ) {
3938 if ( $object !== false ) {
3939 $ret = array( 'object' => $object );
3941 $ret = array( 'text' => $text );
3944 wfProfileOut( __METHOD__
);
3949 * Return the text to be used for a given extension tag.
3950 * This is the ghost of strip().
3952 * @param array $params Associative array of parameters:
3953 * name PPNode for the tag name
3954 * attr PPNode for unparsed text where tag attributes are thought to be
3955 * attributes Optional associative array of parsed attributes
3956 * inner Contents of extension element
3957 * noClose Original text did not have a close tag
3958 * @param $frame PPFrame
3960 * @throws MWException
3963 function extensionSubstitution( $params, $frame ) {
3964 $name = $frame->expand( $params['name'] );
3965 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3966 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3967 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3969 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3970 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3971 if ( $isFunctionTag ) {
3972 $markerType = 'none';
3974 $markerType = 'general';
3976 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3977 $name = strtolower( $name );
3978 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3979 if ( isset( $params['attributes'] ) ) {
3980 $attributes = $attributes +
$params['attributes'];
3983 if ( isset( $this->mTagHooks
[$name] ) ) {
3984 # Workaround for PHP bug 35229 and similar
3985 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3986 throw new MWException( "Tag hook for $name is not callable\n" );
3988 $output = call_user_func_array( $this->mTagHooks
[$name],
3989 array( $content, $attributes, $this, $frame ) );
3990 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3991 list( $callback, ) = $this->mFunctionTagHooks
[$name];
3992 if ( !is_callable( $callback ) ) {
3993 throw new MWException( "Tag hook for $name is not callable\n" );
3996 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3998 $output = '<span class="error">Invalid tag extension name: ' .
3999 htmlspecialchars( $name ) . '</span>';
4002 if ( is_array( $output ) ) {
4003 # Extract flags to local scope (to override $markerType)
4005 $output = $flags[0];
4010 if ( is_null( $attrText ) ) {
4013 if ( isset( $params['attributes'] ) ) {
4014 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4015 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4016 htmlspecialchars( $attrValue ) . '"';
4019 if ( $content === null ) {
4020 $output = "<$name$attrText/>";
4022 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4023 $output = "<$name$attrText>$content$close";
4027 if ( $markerType === 'none' ) {
4029 } elseif ( $markerType === 'nowiki' ) {
4030 $this->mStripState
->addNoWiki( $marker, $output );
4031 } elseif ( $markerType === 'general' ) {
4032 $this->mStripState
->addGeneral( $marker, $output );
4034 throw new MWException( __METHOD__
. ': invalid marker type' );
4040 * Increment an include size counter
4042 * @param string $type the type of expansion
4043 * @param $size Integer: the size of the text
4044 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
4046 function incrementIncludeSize( $type, $size ) {
4047 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4050 $this->mIncludeSizes
[$type] +
= $size;
4056 * Increment the expensive function count
4058 * @return Boolean: false if the limit has been exceeded
4060 function incrementExpensiveFunctionCount() {
4061 $this->mExpensiveFunctionCount++
;
4062 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4066 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4067 * Fills $this->mDoubleUnderscores, returns the modified text
4069 * @param $text string
4073 function doDoubleUnderscore( $text ) {
4074 wfProfileIn( __METHOD__
);
4076 # The position of __TOC__ needs to be recorded
4077 $mw = MagicWord
::get( 'toc' );
4078 if ( $mw->match( $text ) ) {
4079 $this->mShowToc
= true;
4080 $this->mForceTocPosition
= true;
4082 # Set a placeholder. At the end we'll fill it in with the TOC.
4083 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4085 # Only keep the first one.
4086 $text = $mw->replace( '', $text );
4089 # Now match and remove the rest of them
4090 $mwa = MagicWord
::getDoubleUnderscoreArray();
4091 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4093 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4094 $this->mOutput
->mNoGallery
= true;
4096 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4097 $this->mShowToc
= false;
4099 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
4100 $this->addTrackingCategory( 'hidden-category-category' );
4102 # (bug 8068) Allow control over whether robots index a page.
4104 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4105 # is not desirable, the last one on the page should win.
4106 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4107 $this->mOutput
->setIndexPolicy( 'noindex' );
4108 $this->addTrackingCategory( 'noindex-category' );
4110 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4111 $this->mOutput
->setIndexPolicy( 'index' );
4112 $this->addTrackingCategory( 'index-category' );
4115 # Cache all double underscores in the database
4116 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4117 $this->mOutput
->setProperty( $key, '' );
4120 wfProfileOut( __METHOD__
);
4125 * Add a tracking category, getting the title from a system message,
4126 * or print a debug message if the title is invalid.
4128 * @param string $msg message key
4129 * @return Boolean: whether the addition was successful
4131 public function addTrackingCategory( $msg ) {
4132 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
4133 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
4136 // Important to parse with correct title (bug 31469)
4137 $cat = wfMessage( $msg )
4138 ->title( $this->getTitle() )
4139 ->inContentLanguage()
4142 # Allow tracking categories to be disabled by setting them to "-"
4143 if ( $cat === '-' ) {
4147 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
4148 if ( $containerCategory ) {
4149 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4152 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
4158 * This function accomplishes several tasks:
4159 * 1) Auto-number headings if that option is enabled
4160 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4161 * 3) Add a Table of contents on the top for users who have enabled the option
4162 * 4) Auto-anchor headings
4164 * It loops through all headlines, collects the necessary data, then splits up the
4165 * string and re-inserts the newly formatted headlines.
4167 * @param $text String
4168 * @param string $origText original, untouched wikitext
4169 * @param $isMain Boolean
4170 * @return mixed|string
4173 function formatHeadings( $text, $origText, $isMain = true ) {
4174 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4176 # Inhibit editsection links if requested in the page
4177 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4178 $maybeShowEditLink = $showEditLink = false;
4180 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4181 $showEditLink = $this->mOptions
->getEditSection();
4183 if ( $showEditLink ) {
4184 $this->mOutput
->setEditSectionTokens( true );
4187 # Get all headlines for numbering them and adding funky stuff like [edit]
4188 # links - this is for later, but we need the number of headlines right now
4190 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i', $text, $matches );
4192 # if there are fewer than 4 headlines in the article, do not show TOC
4193 # unless it's been explicitly enabled.
4194 $enoughToc = $this->mShowToc
&&
4195 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4197 # Allow user to stipulate that a page should have a "new section"
4198 # link added via __NEWSECTIONLINK__
4199 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4200 $this->mOutput
->setNewSection( true );
4203 # Allow user to remove the "new section"
4204 # link via __NONEWSECTIONLINK__
4205 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4206 $this->mOutput
->hideNewSection( true );
4209 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4210 # override above conditions and always show TOC above first header
4211 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4212 $this->mShowToc
= true;
4220 # Ugh .. the TOC should have neat indentation levels which can be
4221 # passed to the skin functions. These are determined here
4225 $sublevelCount = array();
4226 $levelCount = array();
4231 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4232 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4233 $oldType = $this->mOutputType
;
4234 $this->setOutputType( self
::OT_WIKI
);
4235 $frame = $this->getPreprocessor()->newFrame();
4236 $root = $this->preprocessToDom( $origText );
4237 $node = $root->getFirstChild();
4242 foreach ( $matches[3] as $headline ) {
4243 $isTemplate = false;
4245 $sectionIndex = false;
4247 $markerMatches = array();
4248 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4249 $serial = $markerMatches[1];
4250 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4251 $isTemplate = ( $titleText != $baseTitleText );
4252 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4256 $prevlevel = $level;
4258 $level = $matches[1][$headlineCount];
4260 if ( $level > $prevlevel ) {
4261 # Increase TOC level
4263 $sublevelCount[$toclevel] = 0;
4264 if ( $toclevel < $wgMaxTocLevel ) {
4265 $prevtoclevel = $toclevel;
4266 $toc .= Linker
::tocIndent();
4269 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4270 # Decrease TOC level, find level to jump to
4272 for ( $i = $toclevel; $i > 0; $i-- ) {
4273 if ( $levelCount[$i] == $level ) {
4274 # Found last matching level
4277 } elseif ( $levelCount[$i] < $level ) {
4278 # Found first matching level below current level
4286 if ( $toclevel < $wgMaxTocLevel ) {
4287 if ( $prevtoclevel < $wgMaxTocLevel ) {
4288 # Unindent only if the previous toc level was shown :p
4289 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4290 $prevtoclevel = $toclevel;
4292 $toc .= Linker
::tocLineEnd();
4296 # No change in level, end TOC line
4297 if ( $toclevel < $wgMaxTocLevel ) {
4298 $toc .= Linker
::tocLineEnd();
4302 $levelCount[$toclevel] = $level;
4304 # count number of headlines for each level
4305 $sublevelCount[$toclevel]++
;
4307 for ( $i = 1; $i <= $toclevel; $i++
) {
4308 if ( !empty( $sublevelCount[$i] ) ) {
4312 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4317 # The safe header is a version of the header text safe to use for links
4319 # Remove link placeholders by the link text.
4320 # <!--LINK number-->
4322 # link text with suffix
4323 # Do this before unstrip since link text can contain strip markers
4324 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4326 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4327 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4329 # Strip out HTML (first regex removes any tag not allowed)
4331 # * <sup> and <sub> (bug 8393)
4334 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4336 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4337 # to allow setting directionality in toc items.
4338 $tocline = preg_replace(
4339 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#' ),
4340 array( '', '<$1>' ),
4343 $tocline = trim( $tocline );
4345 # For the anchor, strip out HTML-y stuff period
4346 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4347 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4349 # Save headline for section edit hint before it's escaped
4350 $headlineHint = $safeHeadline;
4352 if ( $wgExperimentalHtmlIds ) {
4353 # For reverse compatibility, provide an id that's
4354 # HTML4-compatible, like we used to.
4356 # It may be worth noting, academically, that it's possible for
4357 # the legacy anchor to conflict with a non-legacy headline
4358 # anchor on the page. In this case likely the "correct" thing
4359 # would be to either drop the legacy anchors or make sure
4360 # they're numbered first. However, this would require people
4361 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4362 # manually, so let's not bother worrying about it.
4363 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4364 array( 'noninitial', 'legacy' ) );
4365 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4367 if ( $legacyHeadline == $safeHeadline ) {
4368 # No reason to have both (in fact, we can't)
4369 $legacyHeadline = false;
4372 $legacyHeadline = false;
4373 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4377 # HTML names must be case-insensitively unique (bug 10721).
4378 # This does not apply to Unicode characters per
4379 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4380 # @todo FIXME: We may be changing them depending on the current locale.
4381 $arrayKey = strtolower( $safeHeadline );
4382 if ( $legacyHeadline === false ) {
4383 $legacyArrayKey = false;
4385 $legacyArrayKey = strtolower( $legacyHeadline );
4388 # count how many in assoc. array so we can track dupes in anchors
4389 if ( isset( $refers[$arrayKey] ) ) {
4390 $refers[$arrayKey]++
;
4392 $refers[$arrayKey] = 1;
4394 if ( isset( $refers[$legacyArrayKey] ) ) {
4395 $refers[$legacyArrayKey]++
;
4397 $refers[$legacyArrayKey] = 1;
4400 # Don't number the heading if it is the only one (looks silly)
4401 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4402 # the two are different if the line contains a link
4403 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4406 # Create the anchor for linking from the TOC to the section
4407 $anchor = $safeHeadline;
4408 $legacyAnchor = $legacyHeadline;
4409 if ( $refers[$arrayKey] > 1 ) {
4410 $anchor .= '_' . $refers[$arrayKey];
4412 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4413 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4415 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4416 $toc .= Linker
::tocLine( $anchor, $tocline,
4417 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4420 # Add the section to the section tree
4421 # Find the DOM node for this header
4422 while ( $node && !$isTemplate ) {
4423 if ( $node->getName() === 'h' ) {
4424 $bits = $node->splitHeading();
4425 if ( $bits['i'] == $sectionIndex ) {
4429 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4430 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4431 $node = $node->getNextSibling();
4434 'toclevel' => $toclevel,
4437 'number' => $numbering,
4438 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4439 'fromtitle' => $titleText,
4440 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4441 'anchor' => $anchor,
4444 # give headline the correct <h#> tag
4445 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4446 // Output edit section links as markers with styles that can be customized by skins
4447 if ( $isTemplate ) {
4448 # Put a T flag in the section identifier, to indicate to extractSections()
4449 # that sections inside <includeonly> should be counted.
4450 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4452 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4454 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4455 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4456 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4457 // so we don't have to worry about a user trying to input one of these markers directly.
4458 // We use a page and section attribute to stop the language converter from converting these important bits
4459 // of data, but put the headline hint inside a content block because the language converter is supposed to
4460 // be able to convert that piece of data.
4461 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4462 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
4463 if ( isset( $editlinkArgs[2] ) ) {
4464 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4471 $head[$headlineCount] = Linker
::makeHeadline( $level,
4472 $matches['attrib'][$headlineCount], $anchor, $headline,
4473 $editlink, $legacyAnchor );
4478 $this->setOutputType( $oldType );
4480 # Never ever show TOC if no headers
4481 if ( $numVisible < 1 ) {
4486 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4487 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4489 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4490 $this->mOutput
->setTOCHTML( $toc );
4494 $this->mOutput
->setSections( $tocraw );
4497 # split up and insert constructed headlines
4498 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4501 // build an array of document sections
4502 $sections = array();
4503 foreach ( $blocks as $block ) {
4504 // $head is zero-based, sections aren't.
4505 if ( empty( $head[$i - 1] ) ) {
4506 $sections[$i] = $block;
4508 $sections[$i] = $head[$i - 1] . $block;
4512 * Send a hook, one per section.
4513 * The idea here is to be able to make section-level DIVs, but to do so in a
4514 * lower-impact, more correct way than r50769
4517 * $section : the section number
4518 * &$sectionContent : ref to the content of the section
4519 * $showEditLinks : boolean describing whether this section has an edit link
4521 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4526 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4527 // append the TOC at the beginning
4528 // Top anchor now in skin
4529 $sections[0] = $sections[0] . $toc . "\n";
4532 $full .= join( '', $sections );
4534 if ( $this->mForceTocPosition
) {
4535 return str_replace( '<!--MWTOC-->', $toc, $full );
4542 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4543 * conversion, substitting signatures, {{subst:}} templates, etc.
4545 * @param string $text the text to transform
4546 * @param $title Title: the Title object for the current article
4547 * @param $user User: the User object describing the current user
4548 * @param $options ParserOptions: parsing options
4549 * @param $clearState Boolean: whether to clear the parser state first
4550 * @return String: the altered wiki markup
4552 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4553 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4554 $this->setUser( $user );
4559 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4560 if ( $options->getPreSaveTransform() ) {
4561 $text = $this->pstPass2( $text, $user );
4563 $text = $this->mStripState
->unstripBoth( $text );
4565 $this->setUser( null ); #Reset
4571 * Pre-save transform helper function
4574 * @param $text string
4579 function pstPass2( $text, $user ) {
4582 # Note: This is the timestamp saved as hardcoded wikitext to
4583 # the database, we use $wgContLang here in order to give
4584 # everyone the same signature and use the default one rather
4585 # than the one selected in each user's preferences.
4586 # (see also bug 12815)
4587 $ts = $this->mOptions
->getTimestamp();
4588 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4589 $ts = $timestamp->format( 'YmdHis' );
4590 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4592 # Allow translation of timezones through wiki. format() can return
4593 # whatever crap the system uses, localised or not, so we cannot
4594 # ship premade translations.
4595 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4596 $msg = wfMessage( $key )->inContentLanguage();
4597 if ( $msg->exists() ) {
4598 $tzMsg = $msg->text();
4601 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4603 # Variable replacement
4604 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4605 $text = $this->replaceVariables( $text );
4607 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4608 # which may corrupt this parser instance via its wfMessage()->text() call-
4611 $sigText = $this->getUserSig( $user );
4612 $text = strtr( $text, array(
4614 '~~~~' => "$sigText $d",
4618 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4619 $tc = '[' . Title
::legalChars() . ']';
4620 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4622 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4623 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] (double-width brackets, added in r40257)
4624 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]] (using either single or double-width comma)
4625 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]] (reverse pipe trick: add context from page title)
4627 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4628 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4629 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4630 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4632 $t = $this->mTitle
->getText();
4634 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4635 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4636 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4637 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4639 # if there's no context, don't bother duplicating the title
4640 $text = preg_replace( $p2, '[[\\1]]', $text );
4643 # Trim trailing whitespace
4644 $text = rtrim( $text );
4650 * Fetch the user's signature text, if any, and normalize to
4651 * validated, ready-to-insert wikitext.
4652 * If you have pre-fetched the nickname or the fancySig option, you can
4653 * specify them here to save a database query.
4654 * Do not reuse this parser instance after calling getUserSig(),
4655 * as it may have changed if it's the $wgParser.
4658 * @param string|bool $nickname nickname to use or false to use user's default nickname
4659 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4660 * or null to use default value
4663 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4664 global $wgMaxSigChars;
4666 $username = $user->getName();
4668 # If not given, retrieve from the user object.
4669 if ( $nickname === false ) {
4670 $nickname = $user->getOption( 'nickname' );
4673 if ( is_null( $fancySig ) ) {
4674 $fancySig = $user->getBoolOption( 'fancysig' );
4677 $nickname = $nickname == null ?
$username : $nickname;
4679 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4680 $nickname = $username;
4681 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4682 } elseif ( $fancySig !== false ) {
4683 # Sig. might contain markup; validate this
4684 if ( $this->validateSig( $nickname ) !== false ) {
4685 # Validated; clean up (if needed) and return it
4686 return $this->cleanSig( $nickname, true );
4688 # Failed to validate; fall back to the default
4689 $nickname = $username;
4690 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4694 # Make sure nickname doesnt get a sig in a sig
4695 $nickname = self
::cleanSigInSig( $nickname );
4697 # If we're still here, make it a link to the user page
4698 $userText = wfEscapeWikiText( $username );
4699 $nickText = wfEscapeWikiText( $nickname );
4700 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4702 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4706 * Check that the user's signature contains no bad XML
4708 * @param $text String
4709 * @return mixed An expanded string, or false if invalid.
4711 function validateSig( $text ) {
4712 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4716 * Clean up signature text
4718 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4719 * 2) Substitute all transclusions
4721 * @param $text String
4722 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4723 * @return String: signature text
4725 public function cleanSig( $text, $parsing = false ) {
4728 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4731 # Option to disable this feature
4732 if ( !$this->mOptions
->getCleanSignatures() ) {
4736 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4737 # => Move this logic to braceSubstitution()
4738 $substWord = MagicWord
::get( 'subst' );
4739 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4740 $substText = '{{' . $substWord->getSynonym( 0 );
4742 $text = preg_replace( $substRegex, $substText, $text );
4743 $text = self
::cleanSigInSig( $text );
4744 $dom = $this->preprocessToDom( $text );
4745 $frame = $this->getPreprocessor()->newFrame();
4746 $text = $frame->expand( $dom );
4749 $text = $this->mStripState
->unstripBoth( $text );
4756 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4758 * @param $text String
4759 * @return String: signature text with /~{3,5}/ removed
4761 public static function cleanSigInSig( $text ) {
4762 $text = preg_replace( '/~{3,5}/', '', $text );
4767 * Set up some variables which are usually set up in parse()
4768 * so that an external function can call some class members with confidence
4770 * @param $title Title|null
4771 * @param $options ParserOptions
4772 * @param $outputType
4773 * @param $clearState bool
4775 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4776 $this->startParse( $title, $options, $outputType, $clearState );
4780 * @param $title Title|null
4781 * @param $options ParserOptions
4782 * @param $outputType
4783 * @param $clearState bool
4785 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4786 $this->setTitle( $title );
4787 $this->mOptions
= $options;
4788 $this->setOutputType( $outputType );
4789 if ( $clearState ) {
4790 $this->clearState();
4795 * Wrapper for preprocess()
4797 * @param string $text the text to preprocess
4798 * @param $options ParserOptions: options
4799 * @param $title Title object or null to use $wgTitle
4802 public function transformMsg( $text, $options, $title = null ) {
4803 static $executing = false;
4805 # Guard against infinite recursion
4811 wfProfileIn( __METHOD__
);
4817 $text = $this->preprocess( $text, $title, $options );
4820 wfProfileOut( __METHOD__
);
4825 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4826 * The callback should have the following form:
4827 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4829 * Transform and return $text. Use $parser for any required context, e.g. use
4830 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4832 * Hooks may return extended information by returning an array, of which the
4833 * first numbered element (index 0) must be the return string, and all other
4834 * entries are extracted into local variables within an internal function
4835 * in the Parser class.
4837 * This interface (introduced r61913) appears to be undocumented, but
4838 * 'markerName' is used by some core tag hooks to override which strip
4839 * array their results are placed in. **Use great caution if attempting
4840 * this interface, as it is not documented and injudicious use could smash
4841 * private variables.**
4843 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4844 * @param $callback Mixed: the callback function (and object) to use for the tag
4845 * @throws MWException
4846 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4848 public function setHook( $tag, $callback ) {
4849 $tag = strtolower( $tag );
4850 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4851 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4853 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4854 $this->mTagHooks
[$tag] = $callback;
4855 if ( !in_array( $tag, $this->mStripList
) ) {
4856 $this->mStripList
[] = $tag;
4863 * As setHook(), but letting the contents be parsed.
4865 * Transparent tag hooks are like regular XML-style tag hooks, except they
4866 * operate late in the transformation sequence, on HTML instead of wikitext.
4868 * This is probably obsoleted by things dealing with parser frames?
4869 * The only extension currently using it is geoserver.
4872 * @todo better document or deprecate this
4874 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4875 * @param $callback Mixed: the callback function (and object) to use for the tag
4876 * @throws MWException
4877 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4879 function setTransparentTagHook( $tag, $callback ) {
4880 $tag = strtolower( $tag );
4881 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4882 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4884 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4885 $this->mTransparentTagHooks
[$tag] = $callback;
4891 * Remove all tag hooks
4893 function clearTagHooks() {
4894 $this->mTagHooks
= array();
4895 $this->mFunctionTagHooks
= array();
4896 $this->mStripList
= $this->mDefaultStripList
;
4900 * Create a function, e.g. {{sum:1|2|3}}
4901 * The callback function should have the form:
4902 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4904 * Or with SFH_OBJECT_ARGS:
4905 * function myParserFunction( $parser, $frame, $args ) { ... }
4907 * The callback may either return the text result of the function, or an array with the text
4908 * in element 0, and a number of flags in the other elements. The names of the flags are
4909 * specified in the keys. Valid flags are:
4910 * found The text returned is valid, stop processing the template. This
4912 * nowiki Wiki markup in the return value should be escaped
4913 * isHTML The returned text is HTML, armour it against wikitext transformation
4915 * @param string $id The magic word ID
4916 * @param $callback Mixed: the callback function (and object) to use
4917 * @param $flags Integer: a combination of the following flags:
4918 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4920 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4921 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4922 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4923 * the arguments, and to control the way they are expanded.
4925 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4926 * arguments, for instance:
4927 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4929 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4930 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4931 * working if/when this is changed.
4933 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4936 * Please read the documentation in includes/parser/Preprocessor.php for more information
4937 * about the methods available in PPFrame and PPNode.
4939 * @throws MWException
4940 * @return string|callback The old callback function for this name, if any
4942 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4945 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4946 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4948 # Add to function cache
4949 $mw = MagicWord
::get( $id );
4951 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4954 $synonyms = $mw->getSynonyms();
4955 $sensitive = intval( $mw->isCaseSensitive() );
4957 foreach ( $synonyms as $syn ) {
4959 if ( !$sensitive ) {
4960 $syn = $wgContLang->lc( $syn );
4963 if ( !( $flags & SFH_NO_HASH
) ) {
4966 # Remove trailing colon
4967 if ( substr( $syn, -1, 1 ) === ':' ) {
4968 $syn = substr( $syn, 0, -1 );
4970 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4976 * Get all registered function hook identifiers
4980 function getFunctionHooks() {
4981 return array_keys( $this->mFunctionHooks
);
4985 * Create a tag function, e.g. "<test>some stuff</test>".
4986 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4987 * Unlike parser functions, their content is not preprocessed.
4991 * @throws MWException
4994 function setFunctionTagHook( $tag, $callback, $flags ) {
4995 $tag = strtolower( $tag );
4996 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4997 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4999 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5000 $this->mFunctionTagHooks
[$tag] : null;
5001 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5003 if ( !in_array( $tag, $this->mStripList
) ) {
5004 $this->mStripList
[] = $tag;
5011 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5012 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5013 * Placeholders created in Skin::makeLinkObj()
5015 * @param $text string
5016 * @param $options int
5018 * @return array of link CSS classes, indexed by PDBK.
5020 function replaceLinkHolders( &$text, $options = 0 ) {
5021 return $this->mLinkHolders
->replace( $text );
5025 * Replace "<!--LINK-->" link placeholders with plain text of links
5026 * (not HTML-formatted).
5028 * @param $text String
5031 function replaceLinkHoldersText( $text ) {
5032 return $this->mLinkHolders
->replaceText( $text );
5036 * Renders an image gallery from a text with one line per image.
5037 * text labels may be given by using |-style alternative text. E.g.
5038 * Image:one.jpg|The number "1"
5039 * Image:tree.jpg|A tree
5040 * given as text will return the HTML of a gallery with two images,
5041 * labeled 'The number "1"' and
5044 * @param string $text
5045 * @param array $params
5046 * @return string HTML
5048 function renderImageGallery( $text, $params ) {
5049 wfProfileIn( __METHOD__
);
5052 if ( isset( $params['mode'] ) ) {
5053 $mode = $params['mode'];
5057 $ig = ImageGalleryBase
::factory( $mode );
5058 } catch ( MWException
$e ) {
5059 // If invalid type set, fallback to default.
5060 $ig = ImageGalleryBase
::factory( false );
5063 $ig->setContextTitle( $this->mTitle
);
5064 $ig->setShowBytes( false );
5065 $ig->setShowFilename( false );
5066 $ig->setParser( $this );
5067 $ig->setHideBadImages();
5068 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5070 if ( isset( $params['showfilename'] ) ) {
5071 $ig->setShowFilename( true );
5073 $ig->setShowFilename( false );
5075 if ( isset( $params['caption'] ) ) {
5076 $caption = $params['caption'];
5077 $caption = htmlspecialchars( $caption );
5078 $caption = $this->replaceInternalLinks( $caption );
5079 $ig->setCaptionHtml( $caption );
5081 if ( isset( $params['perrow'] ) ) {
5082 $ig->setPerRow( $params['perrow'] );
5084 if ( isset( $params['widths'] ) ) {
5085 $ig->setWidths( $params['widths'] );
5087 if ( isset( $params['heights'] ) ) {
5088 $ig->setHeights( $params['heights'] );
5090 $ig->setAdditionalOptions( $params );
5092 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5094 $lines = StringUtils
::explode( "\n", $text );
5095 foreach ( $lines as $line ) {
5096 # match lines like these:
5097 # Image:someimage.jpg|This is some image
5099 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5101 if ( count( $matches ) == 0 ) {
5105 if ( strpos( $matches[0], '%' ) !== false ) {
5106 $matches[1] = rawurldecode( $matches[1] );
5108 $title = Title
::newFromText( $matches[1], NS_FILE
);
5109 if ( is_null( $title ) ) {
5110 # Bogus title. Ignore these so we don't bomb out later.
5114 # We need to get what handler the file uses, to figure out parameters.
5115 # Note, a hook can overide the file name, and chose an entirely different
5116 # file (which potentially could be of a different type and have different handler).
5119 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5120 array( $this, $title, &$options, &$descQuery ) );
5121 # Don't register it now, as ImageGallery does that later.
5122 $file = $this->fetchFileNoRegister( $title, $options );
5123 $handler = $file ?
$file->getHandler() : false;
5125 wfProfileIn( __METHOD__
. '-getMagicWord' );
5127 'img_alt' => 'gallery-internal-alt',
5128 'img_link' => 'gallery-internal-link',
5131 $paramMap = $paramMap +
$handler->getParamMap();
5132 // We don't want people to specify per-image widths.
5133 // Additionally the width parameter would need special casing anyhow.
5134 unset( $paramMap['img_width'] );
5137 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5138 wfProfileOut( __METHOD__
. '-getMagicWord' );
5143 $handlerOptions = array();
5144 if ( isset( $matches[3] ) ) {
5145 // look for an |alt= definition while trying not to break existing
5146 // captions with multiple pipes (|) in it, until a more sensible grammar
5147 // is defined for images in galleries
5149 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5150 // splitting on '|' is a bit odd, and different from makeImage.
5151 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5152 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5154 foreach ( $parameterMatches as $parameterMatch ) {
5155 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5157 $paramName = $paramMap[$magicName];
5159 switch( $paramName ) {
5160 case 'gallery-internal-alt':
5161 $alt = $this->stripAltText( $match, false );
5163 case 'gallery-internal-link':
5164 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5165 $chars = self
::EXT_LINK_URL_CLASS
;
5166 $prots = $this->mUrlProtocols
;
5167 //check to see if link matches an absolute url, if not then it must be a wiki link.
5168 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5171 $localLinkTitle = Title
::newFromText( $linkValue );
5172 if ( $localLinkTitle !== null ) {
5173 $link = $localLinkTitle->getLocalURL();
5178 // Must be a handler specific parameter.
5179 if ( $handler->validateParam( $paramName, $match ) ) {
5180 $handlerOptions[$paramName] = $match;
5182 // Guess not. Append it to the caption.
5183 wfDebug( "$parameterMatch failed parameter validation" );
5184 $label .= '|' . $parameterMatch;
5189 // concatenate all other pipes
5190 $label .= '|' . $parameterMatch;
5193 // remove the first pipe
5194 $label = substr( $label, 1 );
5197 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5199 $html = $ig->toHTML();
5200 wfProfileOut( __METHOD__
);
5208 function getImageParams( $handler ) {
5210 $handlerClass = get_class( $handler );
5214 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5215 # Initialise static lists
5216 static $internalParamNames = array(
5217 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5218 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5219 'bottom', 'text-bottom' ),
5220 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5221 'upright', 'border', 'link', 'alt', 'class' ),
5223 static $internalParamMap;
5224 if ( !$internalParamMap ) {
5225 $internalParamMap = array();
5226 foreach ( $internalParamNames as $type => $names ) {
5227 foreach ( $names as $name ) {
5228 $magicName = str_replace( '-', '_', "img_$name" );
5229 $internalParamMap[$magicName] = array( $type, $name );
5234 # Add handler params
5235 $paramMap = $internalParamMap;
5237 $handlerParamMap = $handler->getParamMap();
5238 foreach ( $handlerParamMap as $magic => $paramName ) {
5239 $paramMap[$magic] = array( 'handler', $paramName );
5242 $this->mImageParams
[$handlerClass] = $paramMap;
5243 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5245 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5249 * Parse image options text and use it to make an image
5251 * @param $title Title
5252 * @param $options String
5253 * @param $holders LinkHolderArray|bool
5254 * @return string HTML
5256 function makeImage( $title, $options, $holders = false ) {
5257 # Check if the options text is of the form "options|alt text"
5259 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5260 # * left no resizing, just left align. label is used for alt= only
5261 # * right same, but right aligned
5262 # * none same, but not aligned
5263 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5264 # * center center the image
5265 # * frame Keep original image size, no magnify-button.
5266 # * framed Same as "frame"
5267 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5268 # * upright reduce width for upright images, rounded to full __0 px
5269 # * border draw a 1px border around the image
5270 # * alt Text for HTML alt attribute (defaults to empty)
5271 # * class Set a class for img node
5272 # * link Set the target of the image link. Can be external, interwiki, or local
5273 # vertical-align values (no % or length right now):
5283 $parts = StringUtils
::explode( "|", $options );
5285 # Give extensions a chance to select the file revision for us
5288 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5289 array( $this, $title, &$options, &$descQuery ) );
5290 # Fetch and register the file (file title may be different via hooks)
5291 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5294 $handler = $file ?
$file->getHandler() : false;
5296 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5299 $this->addTrackingCategory( 'broken-file-category' );
5302 # Process the input parameters
5304 $params = array( 'frame' => array(), 'handler' => array(),
5305 'horizAlign' => array(), 'vertAlign' => array() );
5306 foreach ( $parts as $part ) {
5307 $part = trim( $part );
5308 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5310 if ( isset( $paramMap[$magicName] ) ) {
5311 list( $type, $paramName ) = $paramMap[$magicName];
5313 # Special case; width and height come in one variable together
5314 if ( $type === 'handler' && $paramName === 'width' ) {
5315 $parsedWidthParam = $this->parseWidthParam( $value );
5316 if ( isset( $parsedWidthParam['width'] ) ) {
5317 $width = $parsedWidthParam['width'];
5318 if ( $handler->validateParam( 'width', $width ) ) {
5319 $params[$type]['width'] = $width;
5323 if ( isset( $parsedWidthParam['height'] ) ) {
5324 $height = $parsedWidthParam['height'];
5325 if ( $handler->validateParam( 'height', $height ) ) {
5326 $params[$type]['height'] = $height;
5330 # else no validation -- bug 13436
5332 if ( $type === 'handler' ) {
5333 # Validate handler parameter
5334 $validated = $handler->validateParam( $paramName, $value );
5336 # Validate internal parameters
5337 switch ( $paramName ) {
5341 # @todo FIXME: Possibly check validity here for
5342 # manualthumb? downstream behavior seems odd with
5343 # missing manual thumbs.
5345 $value = $this->stripAltText( $value, $holders );
5348 $chars = self
::EXT_LINK_URL_CLASS
;
5349 $prots = $this->mUrlProtocols
;
5350 if ( $value === '' ) {
5351 $paramName = 'no-link';
5354 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5355 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5356 $paramName = 'link-url';
5357 $this->mOutput
->addExternalLink( $value );
5358 if ( $this->mOptions
->getExternalLinkTarget() ) {
5359 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5364 $linkTitle = Title
::newFromText( $value );
5366 $paramName = 'link-title';
5367 $value = $linkTitle;
5368 $this->mOutput
->addLink( $linkTitle );
5374 # Most other things appear to be empty or numeric...
5375 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5380 $params[$type][$paramName] = $value;
5384 if ( !$validated ) {
5389 # Process alignment parameters
5390 if ( $params['horizAlign'] ) {
5391 $params['frame']['align'] = key( $params['horizAlign'] );
5393 if ( $params['vertAlign'] ) {
5394 $params['frame']['valign'] = key( $params['vertAlign'] );
5397 $params['frame']['caption'] = $caption;
5399 # Will the image be presented in a frame, with the caption below?
5400 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5401 isset( $params['frame']['framed'] ) ||
5402 isset( $params['frame']['thumbnail'] ) ||
5403 isset( $params['frame']['manualthumb'] );
5405 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5406 # came to also set the caption, ordinary text after the image -- which
5407 # makes no sense, because that just repeats the text multiple times in
5408 # screen readers. It *also* came to set the title attribute.
5410 # Now that we have an alt attribute, we should not set the alt text to
5411 # equal the caption: that's worse than useless, it just repeats the
5412 # text. This is the framed/thumbnail case. If there's no caption, we
5413 # use the unnamed parameter for alt text as well, just for the time be-
5414 # ing, if the unnamed param is set and the alt param is not.
5416 # For the future, we need to figure out if we want to tweak this more,
5417 # e.g., introducing a title= parameter for the title; ignoring the un-
5418 # named parameter entirely for images without a caption; adding an ex-
5419 # plicit caption= parameter and preserving the old magic unnamed para-
5421 if ( $imageIsFramed ) { # Framed image
5422 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5423 # No caption or alt text, add the filename as the alt text so
5424 # that screen readers at least get some description of the image
5425 $params['frame']['alt'] = $title->getText();
5427 # Do not set $params['frame']['title'] because tooltips don't make sense
5429 } else { # Inline image
5430 if ( !isset( $params['frame']['alt'] ) ) {
5431 # No alt text, use the "caption" for the alt text
5432 if ( $caption !== '' ) {
5433 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5435 # No caption, fall back to using the filename for the
5437 $params['frame']['alt'] = $title->getText();
5440 # Use the "caption" for the tooltip text
5441 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5444 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5446 # Linker does the rest
5447 $time = isset( $options['time'] ) ?
$options['time'] : false;
5448 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5449 $time, $descQuery, $this->mOptions
->getThumbSize() );
5451 # Give the handler a chance to modify the parser object
5453 $handler->parserTransformHook( $this, $file );
5461 * @param $holders LinkHolderArray
5462 * @return mixed|String
5464 protected function stripAltText( $caption, $holders ) {
5465 # Strip bad stuff out of the title (tooltip). We can't just use
5466 # replaceLinkHoldersText() here, because if this function is called
5467 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5469 $tooltip = $holders->replaceText( $caption );
5471 $tooltip = $this->replaceLinkHoldersText( $caption );
5474 # make sure there are no placeholders in thumbnail attributes
5475 # that are later expanded to html- so expand them now and
5477 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5478 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5484 * Set a flag in the output object indicating that the content is dynamic and
5485 * shouldn't be cached.
5487 function disableCache() {
5488 wfDebug( "Parser output marked as uncacheable.\n" );
5489 if ( !$this->mOutput
) {
5490 throw new MWException( __METHOD__
.
5491 " can only be called when actually parsing something" );
5493 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5494 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5498 * Callback from the Sanitizer for expanding items found in HTML attribute
5499 * values, so they can be safely tested and escaped.
5501 * @param $text String
5502 * @param $frame PPFrame
5505 function attributeStripCallback( &$text, $frame = false ) {
5506 $text = $this->replaceVariables( $text, $frame );
5507 $text = $this->mStripState
->unstripBoth( $text );
5516 function getTags() {
5517 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5521 * Replace transparent tags in $text with the values given by the callbacks.
5523 * Transparent tag hooks are like regular XML-style tag hooks, except they
5524 * operate late in the transformation sequence, on HTML instead of wikitext.
5526 * @param $text string
5530 function replaceTransparentTags( $text ) {
5532 $elements = array_keys( $this->mTransparentTagHooks
);
5533 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5534 $replacements = array();
5536 foreach ( $matches as $marker => $data ) {
5537 list( $element, $content, $params, $tag ) = $data;
5538 $tagName = strtolower( $element );
5539 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5540 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5544 $replacements[$marker] = $output;
5546 return strtr( $text, $replacements );
5550 * Break wikitext input into sections, and either pull or replace
5551 * some particular section's text.
5553 * External callers should use the getSection and replaceSection methods.
5555 * @param string $text Page wikitext
5556 * @param string $section a section identifier string of the form:
5557 * "<flag1> - <flag2> - ... - <section number>"
5559 * Currently the only recognised flag is "T", which means the target section number
5560 * was derived during a template inclusion parse, in other words this is a template
5561 * section edit link. If no flags are given, it was an ordinary section edit link.
5562 * This flag is required to avoid a section numbering mismatch when a section is
5563 * enclosed by "<includeonly>" (bug 6563).
5565 * The section number 0 pulls the text before the first heading; other numbers will
5566 * pull the given section along with its lower-level subsections. If the section is
5567 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5569 * Section 0 is always considered to exist, even if it only contains the empty
5570 * string. If $text is the empty string and section 0 is replaced, $newText is
5573 * @param string $mode one of "get" or "replace"
5574 * @param string $newText replacement text for section data.
5575 * @return String: for "get", the extracted section text.
5576 * for "replace", the whole page with the section replaced.
5578 private function extractSections( $text, $section, $mode, $newText = '' ) {
5579 global $wgTitle; # not generally used but removes an ugly failure mode
5580 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5582 $frame = $this->getPreprocessor()->newFrame();
5584 # Process section extraction flags
5586 $sectionParts = explode( '-', $section );
5587 $sectionIndex = array_pop( $sectionParts );
5588 foreach ( $sectionParts as $part ) {
5589 if ( $part === 'T' ) {
5590 $flags |
= self
::PTD_FOR_INCLUSION
;
5594 # Check for empty input
5595 if ( strval( $text ) === '' ) {
5596 # Only sections 0 and T-0 exist in an empty document
5597 if ( $sectionIndex == 0 ) {
5598 if ( $mode === 'get' ) {
5604 if ( $mode === 'get' ) {
5612 # Preprocess the text
5613 $root = $this->preprocessToDom( $text, $flags );
5615 # <h> nodes indicate section breaks
5616 # They can only occur at the top level, so we can find them by iterating the root's children
5617 $node = $root->getFirstChild();
5619 # Find the target section
5620 if ( $sectionIndex == 0 ) {
5621 # Section zero doesn't nest, level=big
5622 $targetLevel = 1000;
5625 if ( $node->getName() === 'h' ) {
5626 $bits = $node->splitHeading();
5627 if ( $bits['i'] == $sectionIndex ) {
5628 $targetLevel = $bits['level'];
5632 if ( $mode === 'replace' ) {
5633 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5635 $node = $node->getNextSibling();
5641 if ( $mode === 'get' ) {
5648 # Find the end of the section, including nested sections
5650 if ( $node->getName() === 'h' ) {
5651 $bits = $node->splitHeading();
5652 $curLevel = $bits['level'];
5653 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5657 if ( $mode === 'get' ) {
5658 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5660 $node = $node->getNextSibling();
5663 # Write out the remainder (in replace mode only)
5664 if ( $mode === 'replace' ) {
5665 # Output the replacement text
5666 # Add two newlines on -- trailing whitespace in $newText is conventionally
5667 # stripped by the editor, so we need both newlines to restore the paragraph gap
5668 # Only add trailing whitespace if there is newText
5669 if ( $newText != "" ) {
5670 $outText .= $newText . "\n\n";
5674 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5675 $node = $node->getNextSibling();
5679 if ( is_string( $outText ) ) {
5680 # Re-insert stripped tags
5681 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5688 * This function returns the text of a section, specified by a number ($section).
5689 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5690 * the first section before any such heading (section 0).
5692 * If a section contains subsections, these are also returned.
5694 * @param string $text text to look in
5695 * @param string $section section identifier
5696 * @param string $deftext default to return if section is not found
5697 * @return string text of the requested section
5699 public function getSection( $text, $section, $deftext = '' ) {
5700 return $this->extractSections( $text, $section, "get", $deftext );
5704 * This function returns $oldtext after the content of the section
5705 * specified by $section has been replaced with $text. If the target
5706 * section does not exist, $oldtext is returned unchanged.
5708 * @param string $oldtext former text of the article
5709 * @param int $section section identifier
5710 * @param string $text replacing text
5711 * @return String: modified text
5713 public function replaceSection( $oldtext, $section, $text ) {
5714 return $this->extractSections( $oldtext, $section, "replace", $text );
5718 * Get the ID of the revision we are parsing
5720 * @return Mixed: integer or null
5722 function getRevisionId() {
5723 return $this->mRevisionId
;
5727 * Get the revision object for $this->mRevisionId
5729 * @return Revision|null either a Revision object or null
5731 protected function getRevisionObject() {
5732 if ( !is_null( $this->mRevisionObject
) ) {
5733 return $this->mRevisionObject
;
5735 if ( is_null( $this->mRevisionId
) ) {
5739 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5740 return $this->mRevisionObject
;
5744 * Get the timestamp associated with the current revision, adjusted for
5745 * the default server-local timestamp
5747 function getRevisionTimestamp() {
5748 if ( is_null( $this->mRevisionTimestamp
) ) {
5749 wfProfileIn( __METHOD__
);
5753 $revObject = $this->getRevisionObject();
5754 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5756 # The cryptic '' timezone parameter tells to use the site-default
5757 # timezone offset instead of the user settings.
5759 # Since this value will be saved into the parser cache, served
5760 # to other users, and potentially even used inside links and such,
5761 # it needs to be consistent for all visitors.
5762 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5764 wfProfileOut( __METHOD__
);
5766 return $this->mRevisionTimestamp
;
5770 * Get the name of the user that edited the last revision
5772 * @return String: user name
5774 function getRevisionUser() {
5775 if ( is_null( $this->mRevisionUser
) ) {
5776 $revObject = $this->getRevisionObject();
5778 # if this template is subst: the revision id will be blank,
5779 # so just use the current user's name
5781 $this->mRevisionUser
= $revObject->getUserText();
5782 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5783 $this->mRevisionUser
= $this->getUser()->getName();
5786 return $this->mRevisionUser
;
5790 * Mutator for $mDefaultSort
5792 * @param string $sort New value
5794 public function setDefaultSort( $sort ) {
5795 $this->mDefaultSort
= $sort;
5796 $this->mOutput
->setProperty( 'defaultsort', $sort );
5800 * Accessor for $mDefaultSort
5801 * Will use the empty string if none is set.
5803 * This value is treated as a prefix, so the
5804 * empty string is equivalent to sorting by
5809 public function getDefaultSort() {
5810 if ( $this->mDefaultSort
!== false ) {
5811 return $this->mDefaultSort
;
5818 * Accessor for $mDefaultSort
5819 * Unlike getDefaultSort(), will return false if none is set
5821 * @return string or false
5823 public function getCustomDefaultSort() {
5824 return $this->mDefaultSort
;
5828 * Try to guess the section anchor name based on a wikitext fragment
5829 * presumably extracted from a heading, for example "Header" from
5832 * @param $text string
5836 public function guessSectionNameFromWikiText( $text ) {
5837 # Strip out wikitext links(they break the anchor)
5838 $text = $this->stripSectionName( $text );
5839 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5840 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5844 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5845 * instead. For use in redirects, since IE6 interprets Redirect: headers
5846 * as something other than UTF-8 (apparently?), resulting in breakage.
5848 * @param string $text The section name
5849 * @return string An anchor
5851 public function guessLegacySectionNameFromWikiText( $text ) {
5852 # Strip out wikitext links(they break the anchor)
5853 $text = $this->stripSectionName( $text );
5854 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5855 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5859 * Strips a text string of wikitext for use in a section anchor
5861 * Accepts a text string and then removes all wikitext from the
5862 * string and leaves only the resultant text (i.e. the result of
5863 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5864 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5865 * to create valid section anchors by mimicing the output of the
5866 * parser when headings are parsed.
5868 * @param string $text text string to be stripped of wikitext
5869 * for use in a Section anchor
5870 * @return string Filtered text string
5872 public function stripSectionName( $text ) {
5873 # Strip internal link markup
5874 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5875 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5877 # Strip external link markup
5878 # @todo FIXME: Not tolerant to blank link text
5879 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5880 # on how many empty links there are on the page - need to figure that out.
5881 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5883 # Parse wikitext quotes (italics & bold)
5884 $text = $this->doQuotes( $text );
5887 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5892 * strip/replaceVariables/unstrip for preprocessor regression testing
5894 * @param $text string
5895 * @param $title Title
5896 * @param $options ParserOptions
5897 * @param $outputType int
5901 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5902 $this->startParse( $title, $options, $outputType, true );
5904 $text = $this->replaceVariables( $text );
5905 $text = $this->mStripState
->unstripBoth( $text );
5906 $text = Sanitizer
::removeHTMLtags( $text );
5911 * @param $text string
5912 * @param $title Title
5913 * @param $options ParserOptions
5916 function testPst( $text, Title
$title, ParserOptions
$options ) {
5917 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5922 * @param $title Title
5923 * @param $options ParserOptions
5926 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5927 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5931 * Call a callback function on all regions of the given text that are not
5932 * inside strip markers, and replace those regions with the return value
5933 * of the callback. For example, with input:
5937 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5938 * two strings will be replaced with the value returned by the callback in
5946 function markerSkipCallback( $s, $callback ) {
5949 while ( $i < strlen( $s ) ) {
5950 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5951 if ( $markerStart === false ) {
5952 $out .= call_user_func( $callback, substr( $s, $i ) );
5955 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5956 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5957 if ( $markerEnd === false ) {
5958 $out .= substr( $s, $markerStart );
5961 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5962 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5971 * Remove any strip markers found in the given text.
5973 * @param $text Input string
5976 function killMarkers( $text ) {
5977 return $this->mStripState
->killMarkers( $text );
5981 * Save the parser state required to convert the given half-parsed text to
5982 * HTML. "Half-parsed" in this context means the output of
5983 * recursiveTagParse() or internalParse(). This output has strip markers
5984 * from replaceVariables (extensionSubstitution() etc.), and link
5985 * placeholders from replaceLinkHolders().
5987 * Returns an array which can be serialized and stored persistently. This
5988 * array can later be loaded into another parser instance with
5989 * unserializeHalfParsedText(). The text can then be safely incorporated into
5990 * the return value of a parser hook.
5992 * @param $text string
5996 function serializeHalfParsedText( $text ) {
5997 wfProfileIn( __METHOD__
);
6000 'version' => self
::HALF_PARSED_VERSION
,
6001 'stripState' => $this->mStripState
->getSubState( $text ),
6002 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6004 wfProfileOut( __METHOD__
);
6009 * Load the parser state given in the $data array, which is assumed to
6010 * have been generated by serializeHalfParsedText(). The text contents is
6011 * extracted from the array, and its markers are transformed into markers
6012 * appropriate for the current Parser instance. This transformed text is
6013 * returned, and can be safely included in the return value of a parser
6016 * If the $data array has been stored persistently, the caller should first
6017 * check whether it is still valid, by calling isValidHalfParsedText().
6019 * @param array $data Serialized data
6020 * @throws MWException
6023 function unserializeHalfParsedText( $data ) {
6024 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6025 throw new MWException( __METHOD__
. ': invalid version' );
6028 # First, extract the strip state.
6029 $texts = array( $data['text'] );
6030 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6032 # Now renumber links
6033 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6035 # Should be good to go.
6040 * Returns true if the given array, presumed to be generated by
6041 * serializeHalfParsedText(), is compatible with the current version of the
6044 * @param $data Array
6048 function isValidHalfParsedText( $data ) {
6049 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6053 * Parsed a width param of imagelink like 300px or 200x300px
6055 * @param $value String
6060 public function parseWidthParam( $value ) {
6061 $parsedWidthParam = array();
6062 if ( $value === '' ) {
6063 return $parsedWidthParam;
6066 # (bug 13500) In both cases (width/height and width only),
6067 # permit trailing "px" for backward compatibility.
6068 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6069 $width = intval( $m[1] );
6070 $height = intval( $m[2] );
6071 $parsedWidthParam['width'] = $width;
6072 $parsedWidthParam['height'] = $height;
6073 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6074 $width = intval( $value );
6075 $parsedWidthParam['width'] = $width;
6077 return $parsedWidthParam;